DIY BLUETOOTH SPEAKER

a simple guide to building your own bluetooth speaker on a budget.

I had an idea to build a bluetooth speaker for a long time and last month got the time and components to start the work. Every teen guy here wanted to have loud sounds with high base in the 20s. I guess still we aren’t changed much on that subject. Here is a guide to building a one on your own at a cheap.

Below are the components you need to buy on your next run to the local electronics store. If not you can simply ebay them.
1. bluetooth / USB / FM decoder module
2. PAM8403 amplifier module
3. 2 speakers (4Ω 3W preferable)
4. 5V AC to DC converter

If you have an old radio lying around, you can use those speakers too. Also, I acquired all the items from local electronics store and they are more cheaper than ebay listings. Total cost for the components for me is around 1000 LKR. One thing to note about the decoder module is that it supports many modes including FM, line in, USB MP3, TF card MP3.

Wiring the components are pretty much simple. Refer below image as a guide. Here I didn’t include wiring of 5V supply, you have to solder one end to a AC plug and use the DC output end to power the decoder module and the amplifier. For that, I used an old 2 pin AC plug from a broken soldering iron.

component wiring diagram

After everything is connected, connect the converter to AC and check the decoder module. It will show the current mode on 7-segment display and speak the selected mode out loud. Use the IR remote which came with the decoder to change the mode. Once you are on bluetooth mode, it will speak out loud as “bluetooth mode”. Now the moment of truth 😉

Take your phone and turn on bluetooth and scan for nearby device. Your precious newly made speaker will show as BT-SPEAKER. Tap to pair, select Yes for the initial pin exchange. Once you are paired, the speaker will respond as “paired”. Hit play on your favorite song, make sure both speakers are working.

your speaker will show as ‘BT-SPEAKER’

If everything goes Okey, now it is time to make it pretty. You can use your imagination for that to make it much better than mine. I used a pizza box to house all my components and a glue gun to glue speakers and decoder on to the box.

speaker proudly lying on table.

ADDING CUSTOM LIBRARY (store.js) TO EMBER

here is the quick snippet.
first install the library with bower. bower install store-js --save

now edit ember-cli-build.js file and import the library there.

var EmberApp = require('ember-cli/lib/broccoli/ember-app');

module.exports = function(defaults) {
  ...
  // Use app.import to add additional libraries to the generated
  // output files.

  //Javascript files.
  app.import("bower_components/store-js/dist/store.legacy.min.js");

  return app.toTree();
};

now you can use the library anywhere inside ember by its namespace. in store.js case, it is store.

import Ember from 'ember';

const StorageHandler = Ember.Object.extend({

  get(name) {
    console.log('store get will be called');
    return store.get(name);
  }
}

DEAL WITH YOUR “NOT WORKING” POWER BUTTON – ANDROID

if you own a pretty cheap android phone like xiaomi or any other, after sometime (say 1 year) your buttons will stop working one by one. currently in my redmi note 2, all buttons are not pressable anymore. 😀

you get what you get for your money, can’t expect more.

usually, if your phone comes with plastic buttons for power and volumes +/- buttons, well give it sometime and observe. you’ll need this article someday. 😛

cheap plastic buttons on RN2. picture courtesy: http://www.gsmarena.com/xiaomi_redmi_note_2-pictures-6992.php

the actual reason for buttons not working is not actually with the button materials it self. but it reflects the quality of internal accessory. 😀 real reason behind this is flex cable getting jammed. if you can remove the phone’s back cover and look at the place where buttons actually lie, you can see a small cable fixed-in, in that area with small 3 bubbles which represents the hardware keys in your mobile.

flex cable which can be found in RN2.

so if your power button is not working anymore, you’ll find lot of troubles. you can’t power off / on the phone from hardware button, specially when battery is drained and connected to charger. you can’t wake /lock your screen ? the troubles will get really embarrassing if you didn’t go for a solution quickly.

owkey. time to explore solutions. 😉

1. PERMANENT SOLUTION

just replace the flex cable with a new one. if you are a DIY fan, you can order a one from ebay, watch some DIY videos on youtube and get it done by yourself. it’s not that hard. but here you have to find a temporary solution till your flex cable arrives and till u get some free time to do it.
i am still having this problem, my flex cable didn’t arrive yet. so i had to go with below steps to get my device working till then.

2. TEMPORARY SOLUTION, OR IS IT ?

so your power buttons and volume buttons are not working. can’t turn screen on or off. can’t boot the device ? let’s solve one by one.

2.1 CAN’T WAKE / LOCK SCREEN

solution for this would be use alternative ways to wake / lock the screen.

2.1.1 WAKING UP
2.1.1.1 WAKE WITH VOLUME BUTTONS

you can use volume buttons (if working) to wake up the screen. in MIUI (xiaomi ROM) this functionality can be enabled in settings. but in my case my volumes buttons are also not working, so had to dig deeper.

2.1.1.2 DOUBLE TAP TO WAKE

another way is to use a mechanism like double tap to wake. so you double tap on screen while its off, and the screen will wake up. some ROM vendors had integrated this functionality inside their ROM. if so it’s recommended to enable it from there, rather than depending on a third party app. in MIUI 8 (xiaomi) this functionality can be enabled in settings.

i found a app called knockon which provides the same functionality. didn’t test in on my device though.

2.1.1.3 WAKE WITH MOTION

imagine a scenario, your device will automatically wake up when you needed and it’ll automatically lock when you are not using the phone. this solution is very effective even if your buttons are working, but you are too bored to press it every time you need to wake it up.

using your phone’s inbuilt sensors (context) and with sensor fusion this app (gravity screen) can do an educated guess whether you are holding your phone, lying it on table, it’s in your pocket, you are watching something, etc.
so depending the conclusion, app will automatically wake the screen or lock the screen. i am using it for couple of weeks and it’s surprisingly reliable.

gravity screen app configurations.

once you configured the app as you need, you will never have to press your power button anymore. 😉 (even if it’s working)

2.1.2 TURN OFF SCREEN

this is extremely simple. because unlike in waking up the screen, you can be the one whom in-charge of this action.

2.1.2.1 TOGGLE BUTTON WIDGET

just place a toggle widget to turn off the screen on your home screen.

2.1.2.2 ASSISTIVE TOUCH

or you can be more creative and use an app like assistive touch to have a assitive touch ball on your android like in ios and lock the screen using that.
MIUI 8 (xiaomi) users can enable this feature without any third party app by simply enabling the quick ball feature in settings.

using both toggle widget and assistive touch.
2.1.2.3 LET SENSORS DECIDE

as described in 2.1.1.3 section, you can use gravity screen app to automatically turn off screen when you are not using the phone. just put the phone lying down once you are done, it’ll automatically turn off.

2.2 TURN ON (BOOT) DEVICE

all the solutions i explained earlier are solved using software approaches. but when your device is powered off, we should look at another way to get it booted. 😛

owkey, lets approach it step by step. first of all, when do u need to power on your device ? it should be one of below.

  1. your battery is empty and it was switched off
  2. you intentionally turned it off

 

2.2.1 BATTERY IS EMPTY AND SWITCHED OFF

first thing you have to do when the battery is empty, is to plug your phone to the charger.
when you connect the charger to your phone while it’s switched off, it’ll show a charging indicator but won’t power on. so what if, we could modify that functionality and make it boot when the charger is connected instead of showing the charing indicator screen.

this can be done. for that you will need to first boot the device into fastboot mode and modify some configurations. you need adb tools installed in your PC to continue. if not install them. also make sure you have enabled developer mode and USB debugging in your phone as well.

now connect your phone to PC (while it’s ON), carefully issue below commands. first lets get it booted to fastboot mode.

adb reboot-bootloader

now, your device will reboot into fastboot mode, which we continue to do our modifications.

issue below command and see if your device is identified.

fastboot devices

issue below command and it will print all the system variables on terminal. examine the value returned to off-mode-charge. it should be 1.

fastboot getvar all

..
(bootloader) off-mode-charge: 1  # if its disabled

now we have to set off-mode-charge in to 0 in order to boot the device while the charger is connected. issue below command and verify that you get a similar output.

fastboot getvar all
fastboot oem off-mode-charge 0

..

next reboot the device. issue below command.

fastboot reboot

time to check if it’s working. turn off the phone with assistive touch or any other method and plug in the charger. now your device should boot instead of showing you the charging indicator. 🙂
voila.

2.2.2 INTENTIONALLY TURNED IT OFF

simple, just connect the charger, USB cable or a power bank to phone. 😛 it’ll turn on now according to section 2.2.1.

there is always an alternative way. all you have to do it dig deeper. 😉

references:

CREATE YOUR OWN SMS GATEWAY

here i am gonna show you how to setup a simple sms gateway from a 3G USB dongle using python. the work-flow here is very simple. but before that let’s go through with some basics of 3G USB dongle.

in our gateway once a valid request from the internet is received to our gateway, it should communicate with the dongle and send the message included in the request to the relevant number in the request. so the most important part in this would be communicating with the dongle when the gateway receives some request.

basically your 3G dongle consists with a 3G modem and USB to serial converter. 3G modem is something like below image. to communicate with the modem, it needs a serial (RS-232) connection and this is where USB to serial converter comes to play.
as all modern laptops are consists of USBs this converter is also integrated inside the dongle so we can easily plug it and communicate. so the catch from here is that we can use RS-232 / serial to communicate with our dongle.

GSM / 3G modem module. a tiny compact module is used in a dongle
GSM / 3G modem module. a tiny compact module is used in a dongle

first let’s try to communicate with our dongle with the terminal and if it succeed we can automate that with python to use in our SMS gateway.

GSM / 3G module communication flow.
GSM / 3G module communication flow. source: http://www.engineersgarage.com/articles/gsm-gprs-modules

testing on terminal

first plug the dongle (assuming that you have inserted a sim card with credit in it 😛 ) and find out the port it opened. open terminal and issue dmesg | grep tty command to find out connected USB devices.
you will obtain an output like below.

[   14.124879] usb 1-1.4: GSM modem (1-port) converter now attached to ttyUSB0
[   14.126676] usb 1-1.4: GSM modem (1-port) converter now attached to ttyUSB1
[   14.127795] usb 1-1.4: GSM modem (1-port) converter now attached to ttyUSB2

now, let’s try to communicate with the dongle with the serial connection (RS 232). here we have to use AT commands to communicate. you can find the complete list of AT command set GSM/ 3G modems support from here.

we will be using picocom terminal program to communicate with the dongle via serial. install it as below.

sudo apt-get install picocom

now open the serial port. make sure the substitute relevant port of the dongle.

picocom /dev/ttyUSB0 -b 115200 -l

picocom v1.7

port is        : /dev/gsmmodem
flowcontrol    : none
baudrate is    : 115200
parity is      : none
databits are   : 8
escape is      : C-a
local echo is  : no
noinit is      : no
noreset is     : no
nolock is      : yes
send_cmd is    : sz -vv
receive_cmd is : rz -vv
imap is        : 
omap is        : 
emap is        : crcrlf,delbs,

Terminal ready

try issuing AT command first. you should get an output like following if everything so far alright. 🙂 issue following AT commands as well to make enable text mode for SMS.

AT
OK

AT+CMGF=1
OK

now let’s try to send a message. enter message in following format.
AT+CMGS="phonenumber"<CR>the message to send<ctrl+z>
after the number and the end of double quote hit enter, then type the message. hit ctrl + z.

it’ll give u a OK response and in a while you should receive a text message to your specified number. if all is good, its time to write our gateway piece. 😀

building the gateway

i’ll be using flask for the REST API and a python module called python-messaging for encoding text messages to PDU format.

first install those packages by:

pip install flask
pip install git+https://github.com/pmarti/python-messaging.git

now, lets get into coding. open a new file, say gateway.py. lets first write a function to open the serial port and issue relevant AT command to send the message.

from messaging.sms import SmsSubmit
import serial


def send_text(number, text, path='/dev/ttyUSB0'):
    sms = SmsSubmit(number, text)
    pdu = sms.to_pdu()[0]

    # print len(sms.to_pdu())

    # open the modem port (assumes Linux)
    ser = serial.Serial(path, timeout=1)
    # write the PDU length and wait 1 second till the
    # prompt appears (a more robust implementation
    # would wait till the prompt appeared)
    ser.write('AT+CMGS=%d\r' % pdu.length)
    print ser.readlines()
    # write the PDU and send a ctrl+z escape
    ser.write('%s\x1a' % pdu.pdu)
    ser.close()

now, let’s attach this as a response to a valid POST request. we’ll use HTTP basic auth for authentication.
1. first let’s write a simple function to check user name and password.
2. then basic auth handler to be used in POST request
3. finally the POST request

from flask import Flask, jsonify, request
from functools import wraps
app = Flask(__name__)

def check_auth(username, password):
    """check username / pass"""
    return username == 'user' and password == 'mypassword'


def requires_auth(f):
    @wraps(f)
    def decorated(*args, **kwargs):
        auth = request.authorization
        if not auth or not check_auth(auth.username, auth.password):
            return jsonify({'message': 'not logged in'}), 404
        return f(*args, **kwargs)
    return decorated


@app.route("/")
def hello():
    return "python sms gateway :)"

# POST request handler
@app.route('/send', methods=['POST'])
@requires_auth
def create_task():
    if not request.json or not 'number' in request.json:
        return jsonify({'message': 'no number provided'}), 400

    send_text(request.json['number'], request.json['text'])
    return jsonify({'message': 'message queued'}), 201

if __name__ == "__main__":
    app.run(host='0.0.0.0', port=4000)

so the full code for the gateway will look like below.

gateway.py

from messaging.sms import SmsSubmit
import serial
from flask import Flask, jsonify, request
from functools import wraps
app = Flask(__name__)


def check_auth(username, password):
    """check username / pass"""
    return username == 'user' and password == 'mypassword'


def requires_auth(f):
    @wraps(f)
    def decorated(*args, **kwargs):
        auth = request.authorization
        if not auth or not check_auth(auth.username, auth.password):
            return jsonify({'message': 'not logged in'}), 404
        return f(*args, **kwargs)
    return decorated


def send_text(number, text, path='/dev/ttyUSB0'):
    sms = SmsSubmit(number, text)
    pdu = sms.to_pdu()[0]

    # print len(sms.to_pdu())

    # open the modem port (assumes Linux)
    ser = serial.Serial(path, timeout=1)
    # write the PDU length and wait 1 second till the
    # prompt appears (a more robust implementation
    # would wait till the prompt appeared)
    ser.write('AT+CMGS=%d\r' % pdu.length)
    print ser.readlines()
    # write the PDU and send a ctrl+z escape
    ser.write('%s\x1a' % pdu.pdu)
    ser.close()




@app.route("/")
def hello():
    return "python sms gateway :)"


@app.route('/send', methods=['POST'])
@requires_auth
def create_task():
    if not request.json or not 'number' in request.json:
        return jsonify({'message': 'no number provided'}), 400

    send_text(request.json['number'], request.json['text'])
    return jsonify({'message': 'message queued'}), 201

if __name__ == "__main__":
    app.run(host='0.0.0.0', port=4000)

now run the gateway by issuing python gateway.py. our gateway server now would be running on http://localhost:4000 in the host machine. next let’s use postman to send a test request and ensure that our gateway is working. download postman from chrome web store if you don’t have it installed.

format the request as below. 😛

postman_1

postman_3

if all is good, you should now receive a text from the dongle.

you can find the complete source code of the project from https://github.com/wathmal/sms-gateway.

references:
* https://myraspberryandme.wordpress.com/2013/09/13/short-message-texting-sms-with-huawei-e220/
* https://github.com/pmarti/python-messaging/blob/master/doc/tutorial/sms.rst

RUN APACHE WITH NODE JS REVERSE PROXY – USING REDBIRD

if you are learning or using nodejs, most of you might encounter the problem of running nodejs with apache or nginx. there are several solutions for this issue, with several pros and cons for each solution. for this article i’ll only consider we have a web server with apache.

some of suggested solutions are:

  1. use a reverse proxy with apache (with mod_proxy) to serve nodejs apps
  2. disable apache and run nodejs on port 80 😀
  3. run nodejs on port 80 with a reverse proxy configured on nodejs

if you go with first method, you are really wasting the power of nodejs. but if you do a simple google search on this, lots of articles will suggest you or show you to go with this approach. i am not going to explain this in depth. following extracted text will explain what is the downside of this approach very well. 🙂

you just bought a brand new ferrari and you want to take it for a spin on the highway.. so you go there.. but there is a big fat truck in front of you that only goes 50mph and there is no way to get passed it.

that is basically what you are doing if you put apache (truck) in front of nodejs (ferarri) this defeats one of the main purposes of using nodejs having a FAST evented machine.. which does not allocate threads for requests.

in the second approach, the only downside is you will lost your apache server. so if you run some CMS es like wordpress / drupal you have to find other alternative options like our 3rd solution.

so the 3rd option, running a reverse proxy with nodejs. this idea is really crazy. 😀 following are the steps to do this.

  1. first we have to  make apache run on different port other than port 80.
  2. then configure nodejs to run on port 80.
  3. create the proxy script with redbird.
  4. configure PM2 to auto the start proxy server.

and we are done.

step 1: make apache run on different port

first open ports.conf in /etc/apache2/ directory.

sudo nano /etc/apache2/ports.conf

then change Listen 80 to Listen 8080
so the ports.conf will look like following.

Listen 8080

<IfModule ssl_module>
	Listen 8443
</IfModule>

<IfModule mod_gnutls.c>
	Listen 8443
</IfModule>

next open 000-default.conf in /etc/apache2/sites-available directory.
change <VirtualHost *:80> to the previously given port as <VirtualHost *:8080> and restart the apache server to reflect the changes.

sudo service apache2 restart

step 2: configure nodejs to run on port 80

to run nodejs on port 80, the script will need sudo permission. but there are several ways to do this without sudo permission, which is more safer. we can bind nodejs to listen on lower ports (1 – 1024) by following commands.

sudo apt-get install libcap2-bin
sudo setcap cap_net_bind_service=+ep /usr/local/bin/node

once you do this, we can listen to all lower ports including port 80 via our nodejs app.

step 3: create the proxy script

now we have to write the reverse proxy script. for an example let’s say we have a wordpress blog running with apache on http://mydomain.me:8080/blog/ (in the first step, me made apache run on port 80) and a nodejs app running on http://mydomain.me:3000/ and we want to make both of these apps available on port 80.

to write the proxy script we will be using a npm module called redbird. we can begin writing the script as follows.

 

var proxy = require('redbird')({port: 80, xfwd: false);

proxy.register("mydomain.me/blog", "http://mydomain.me:8080/blog");
proxy.register("mydomain.me", "http://mydomain.me:3000");

note than, this reverse proxy script is set to run on port 80. now if you run this script with node proxy.js we’ll be able to access our blog via http://mydomain.me/blog/ and our node app on port 3000 via http://mydomian.me/. 🙂

step 4: configure PM2 to auto start the proxy server

next step is to making this proxy script auto-start when the system boots. there is a great tool which will do this job for us called PM2. install and configure it if you haven’t already used it.

 

sudo npm install -g pm2
pm2 startup ubuntu

this last line will output a command for you to run on the terminal to make PM2 auto start on system boot. run it and you are almost done.

next step would be adding our proxy script to process list of PM2. then PM2 will take care of our script for us.

pm2 start proxy.js

also via PM2 we can start / stop / restart the process like we use services in linux.

references:
https://groups.google.com/d/msg/nodejs/HX_j8LqFAso/pma5pSQR08IJ
https://github.com/OptimalBits/redbird
https://www.digitalocean.com/community/tutorials/how-to-use-pm2-to-setup-a-node-js-production-environment-on-an-ubuntu-vps

SETTING APACHE REVERSE PROXY FOR TRANSMISSION WEB

howdy fellas! 🙂 today i had to setup apache reverse proxy with my transmission web interface. in my university wifi all ports are blocked other than port 80 and in order to access my transmission server i had to either setup an apache reverse proxy or make transmission daemon run on port 80.

for this, first you have to enable apache mod_proxy and mod_proxy_http modules.

sudo a2enmod proxy
sudo a2enmod proxy_http

next you need to edit the apache configuration file. so first open it with nano.

cd /etc/apache2/sites-available
sudo nano 000-default.conf

your default configuration file name might not same as 000-default.conf. provide the appropriate name.

next you need to add following configuration block to the conf file. here our goal is to access transmission web interface via http://mydomain.me/transmission instead of http://mydomain.me:9091

ProxyRequests Off
<Proxy *>
        AddDefaultCharset off
        Order Allow,Deny
        Allow from all
</Proxy>

ProxyPass /transmission http://mydomain.me:9091/transmission
ProxyPassReverse /transmission http://mydomain.me:9091/transmission

ProxyVia On

following isn’t the reason for HTTP 409 conflict error.
one thing to note is don’t add http://localhost:9091/transmission instead of http://mydomain.me:9091/transmission. in my configuration putting localhost instead of actual domain generated HTTP 409 conflict error.

save the file & exit. next restart the apache server and you are almost done.

sudo service apache2 restart

now you can access your transmission web interface via http://mydomain.me/transmission/web/. 🙂 so happy reverse proxying.

update *
note that you have to access transmission web interface via the exact url as above. if you loose or don’t add /web/ part you’ll receive HTTP 409 conflict error.

SERVER LOAD TESTING NGINX VS APACHE WITH DRUPAL

here is the million dollar questoin! 😀 what is the best web server ? nginx or apache ? if you dig some deep on this, you’ll come around that unless, you have a very big user base or limited hardware resources, it doesn’t matter.

so i wanted to test this with drupal, whether it actually makes a difference in a practical situation. (theoretically it should) thanks to AWS free tier i setup my test environment using AWS as below.

SETTING UP TEST ENVIRONMENT

following are the actions i performed in AWS console and in EC2,

  • launched an EC2 instance
  • launched RDS instance for mysql (for use as drupal’s DB)
  • installed both apache and nginx servers in EC2 instance
  • installed drupal and connected it to RBD server
  • added some dummy content in drupal site

next i created an image of my EC2 instance (AMI) and launched another instance with the same hardware features as previous EC2 instance in same region from the created AMI.

so the next steps followed are,

  • configured one instance to run apache only and another to run nginx only.
  • pointed drupal installation as root directory in both servers.

after this, i had two drupal installations with same content running on apache and nginx in same location.

CREATING A TEST PLAN

so the basic thing i wanted to test is,

server performance in limited hardware over a large traffic.

i used jmeter with performance monitor plugin for this. performance monitor plugin will allow you to measure server performance metrics in jmeter.(cool right ? 🙂 )

for the test plan, in jmeter

  • added thread group with 1000 threads to simulate 1000 users
  • inside thread group added HTTP GET request to root folder to simulate main page access in druapl site
  • added a performance monitor metric collector to measure server CPU & memory usage
  • added a summary report to get overall statistics
jmeter test plan
jmeter test plan

 

RESULTS

so i performed this same test on both of my EC2 instances. following are the results i obtained.

APACHE

requests failed throughput
1000 18.7% 4.437640063/hr
apache server performances for 1000 users
apache server performances

NGINX

requests failed throughput
1000 7.2% 4.4314258999/hr
nginx server performances for 1000 users
nginx server performances

CONCLUSION

so so so, here it is! answer for the million dollar question.

under a large traffic with same hardware resources, nginx performs way better than apache.

references:
https://www.digitalocean.com/community/tutorials/how-to-use-apache-jmeter-to-perform-load-testing-on-a-web-server

HOW PASSIVE AUTO FOCUS WORKS IN CAMERAS

did you ever wonder how your smartphone manage to focus on any place you tap on the camera app? 🙂 okey, even if u did or didn’t now you gonna find how.

to achieve the correct focus, modern digital cameras have come up with 3 approaches such as, ACTIVE, PASSIVE and HYBRID. in ACTIVE approach they use separate sensor mechanism to detect focus. in PASSIVE approach, it uses algorithmic ways to find correct focus from the input of the optical system. there are few ways doing this, i’m gonna show you, how it is done with “contrast detection” method.

so let’s jump into some facts. 😉

when a region is at its sharpest focus, the adjacent pixels in the region will be at maximum contrast. in another word difference between intensity levels in the region is higher than the differences between intensity levels in the region, when the region is not focused.

what will happen to the image mean when it is focused or blurred? so let us take a sample image, make it blur and calculate the mean of those two. i blurred the image using gimp (gaussian blur radius 10px) and calculated image statics using imagemagic.

independent-arcade-lightings independent-arcade-lightings-blurred
Image statistics:
Overall:
min: 0 (0)
max: 255 (1)
mean: 63.7428 (0.249972)
standard deviation: 80.7208 (0.316552)
kurtosis: 0.641563
skewness: 1.33126
Image statistics:
Overall:
min: 0 (0)
max: 255 (1)
mean: 63.7887 (0.250152)
standard deviation: 76.3692 (0.299487)
kurtosis: 0.721282
skewness: 1.30604

identify -verbose independent-arcade-lightings.jpg command will pull out all image statistics of you image.

as you can see, mean of the both original and blurred images is same. 🙂 so image mean does not affect with the focus of the image. also, you can see that standard deviation is the variable which has changed with the blurring. an image’s standard deviation is directly related to its contrast. (standard deviation expresses by how much the members of a group differ from the mean value for the group)

so we can conclude 2 facts about focus.

  1. focus does not affect image mean.
  2. the spread of the pixel intensities (standard deviation) is affected by focusing.

now we have a great way to measure if a region is focused or not. what we want to do is to implement a mechanical control system for the camera lens to achieve the highest possible contrast of the region. and that is what actually comes with PASSIVE AF digital cameras. the system can be modeled like below.

camera auto focus mechanism
camera auto focus mechanism

ABOUT THIS BLOG

so here we are. if you are reading this that means you will be probably thinking what is this shit? 🙂 i mean about the blog!

all the text is lower cased and theme is so so basic … well there is 2 problems with me, i hate capitalized texts and i love being so minimal. i am very sorry if you are troubled when reading posts. 🙁 i just really like this shit and i love this being this. 😉

PORT ROLL-A-BALL UNITY TUTORIAL TO ANDROID

as unity 3d is now available for linux <3 i was playing with it sice then. the first tutorial you will find as a beginner in unity official site is roll-a-ball game which you can find in here. i assume you have completed this and willing to port this to android or ios which is the main intention of this post.

you can build and run this on pc or mobile devices. but if you try to run this on android or a mobile device your player object won’t move as you moved it in pc. this is because we want to configure our player object to use accelerometer or gyroscope data from the mobile device as inputs.

what we did on the player controller script is we took the keyboard input of horizontal and vertical axis and created a 3d vector with having 0 as y component. one thing to make a note here is that in generally in vectors we are considering z axis as the axis which stands vertically from xy plane which governs up/ down movements. but in unity 3d y axis is the one which governs up/down movements. from here on i will use unity grid system for explanations.

unity axis vs cartesian axis
difference between unity axis and cartesian axis
float moveHorizontal= Input.GetAxis("Horizontal");
float moveVertical= Input.GetAxis("Vertical");

Vector3 movement= new Vector3(moveHorizontal, 0.0f, moveVertical);
rb.AddForce(movement* speed);

what we did here was first we generated a 3d vector from keyboard inputs for x and z movements. we made y axis as 0 as we don’t want our player object to move vertically or up/down. then we add the vector multiplied by a scalar as force to our player object. if u think in simple physics we added a force to an object which is a multiply of a vector and scaler. does it ring a bell?? 😛

\large F = m.\dot{a}

we created an acceleration vector from keyboard inputs, and multiplied by the mass and add that force to the player object. the more you increase the mass more force is added, so the rate of change of object’s position will increase.

so the only thing we have to do here is get the acceleration from the mobile device and add it to our acceleration vector. unity’s interface to the input system provides this natively. you can get the acceleration vector from Input.acceleration. as we want to make y axis acceleration zero we can do following.

Vector3 movement= new Vector3(Input.acceleration.x, 0.0f, Input.acceleration.y);
rb.AddForce(movement* speed);

note that here in Input.acceleration.y provides the linear acceleration of y axis in cartesian grid system. we are all set. switch build platform to android and hit build and run. you may need to setup a bundle identifier for the app if you are switching platforms for the first time.

now you can play the game by tilting your phone. 🙂
references:
https://unity3d.com/learn/tutorials/projects/roll-ball-tutorial
http://answers.unity3d.com/answers/887453/view.html