Tuesday, December 28, 2010

Record and Play Audio

Record audio from sound card

function record(filename)
AI=analoginput('winsound');
addchannel(AI, 1);
Fs = 8000;              % Sample Rate is 8000 Hz
set (AI, 'SampleRate', Fs)
duration = 2;           % 2 second acquisition
set(AI, 'SamplesPerTrigger', duration*Fs);
start(AI);
data = getdata(AI);
delete(AI);
wavwrite(data,Fs,filename); % Data will be saved to file

Play audio file

function play(filename)
soundsc(wavread(filename),Fs) % Play the file in specified sample rate

Sunday, December 26, 2010

Download File in a Server-Client Application

This program downloads a mp3 file from server to client using TCP socket connection. AudioFile is a user defined class.

Client Side Code

public void downloadAudio(AudioFile a) {
    File myDir = null;
    try {
        myDir = new File("Downloads");
        myDir.mkdir();
        
        getConnection();
        oos = new ObjectOutputStream(soc.getOutputStream());
        oos.writeObject(a);

        in = new BufferedInputStream(soc.getInputStream());
        File f = new File("Downloads/" + a.getTrackName() + ".mp3");
        out = new FileOutputStream(f);

        int i = 0;
        downloaded = 0;
        
        byte[] bytesIn = new byte[1024];
        while ((i = in.read(bytesIn)) >= 0) {
            out.write(bytesIn, 0, i);
            downloaded += bytesIn.length;
        }
        out.close();
        in.close();
    } catch (Exception e) {
        e.printStackTrace();
        JOptionPane.showMessageDialog(null, e, "Error", JOptionPane.ERROR_MESSAGE);
    }
}

Server Side Code

private void download(File file) {
    try {
        out = new BufferedOutputStream(soc.getOutputStream());
        in = new FileInputStream(file);
        int i = 0;
        byte[] bytesIn = new byte[1024];
        while ((i = in.read(bytesIn)) >= 0) {
            out.write(bytesIn, 0, i);
        }
        out.close();
        in.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

Saturday, December 25, 2010

Parallel Execution Using Multi-Core CPU

This program assumes multi-core CPU and split the process and execute them parallelly.

import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.logging.Level;
import java.util.logging.Logger;

public class parallel {    
    int x[] = new int[1000000];
    float xcl[] = new float[1000000];
    float xcl2[] = new float[1000000];
    float y2[];
    
    void process() throws InterruptedException, BrokenBarrierException{
        //Instantiate values
        for(int i =0; i<1000000;i++){
           xcl[i] = i;
        }
        //Create the executor object
        ExecutorService exec = Executors.newCachedThreadPool();
        //Create of CPU tasks
        class AddTask extends Thread {
              public  int n = 0;
              AddTask(int x){
                //  this.setPriority(10);
                  n = x;
              }
            public void run() {
                for(int i =n; i< n + 500000 -1;i++){
                    for(int j = 0 ; j<10000;j++){
                    x[i] = x[i]+ j;
                   }
                }
                 //Barrier to control thresds
              }
        }
        Runnable t1 = new AddTask(0);
        Runnable t2 = new AddTask(500000);
        exec.submit(t2);
        exec.submit(t1);
        exec.shutdown();
    }
    public static void main(String[] args) throws InterruptedException, BrokenBarrierException {
         (new  parallel()).process();
    }
}

Thursday, December 16, 2010

Send E-Mail

<?php
function spamcheck($field)  {
   $field=filter_var($field, FILTER_SANITIZE_EMAIL);
  if(filter_var($field, FILTER_VALIDATE_EMAIL))    {
    return TRUE;
    }  else    {
    return FALSE;
    }
  }

if (isset($_REQUEST['email']))  {   //if "email" is filled out, proceed
  //check if the email address is invalid
  $mailcheck = spamcheck($_REQUEST['email']);
  if ($mailcheck==FALSE)    {
    echo "Invalid input";
    }  else    {    //send email
    $email = $_REQUEST['email'] ;
    $subject = $_REQUEST['subject'] ;
    $message = $_REQUEST['message'] ;
    mail("bala@gmail.com", "Subject: $subject",
    $message, "From: $email" );
    echo "Thank you for using our mail form";
    }
  }
else  {    //if "email" is not filled out, display the form
  echo "<form method='post' action='secureMail.php'>
  Email: <input name='email' type='text' /><br />
  Subject: <input name='subject' type='text' /><br />
  Message:<br />
  <textarea name='message' rows='15' cols='40'>
  </textarea><br />
  <input type='submit' />
  </form>";
  }
?>

Upload File

<?php
if ((($_FILES["file2"]["type"] == "image/gif")
|| ($_FILES["file2"]["type"] == "image/jpeg")
|| ($_FILES["file2"]["type"] == "image/pjpeg"))
&& ($_FILES["file2"]["size"] < 20000))
  {
  if ($_FILES["file2"]["error"] > 0)
    {
    echo "Return Code: " . $_FILES["file"]["error"] . "<br />";
    }
  else
    {
    echo "Upload: " . $_FILES["file2"]["name"] . "<br />";
    echo "Type: " . $_FILES["file2"]["type"] . "<br />";
    echo "Size: " . ($_FILES["file2"]["size"] / 1024) . " Kb<br />";
    echo "Temp file: " . $_FILES["file2"]["tmp_name"] . "<br />";


    if (file_exists("upload/" . $_FILES["file2"]["name"]))
      {
      echo $_FILES["file2"]["name"] . " already exists. ";
      }
    else
      {
      move_uploaded_file($_FILES["file2"]["tmp_name"],
      "upload/" . $_FILES["file2"]["name"]);
      echo "Stored in: " . "upload/" . $_FILES["file2"]["name"];
      }
    }
  }
else
  {
  echo "Invalid file";
  }
?>

Session

<?php
// STARTING A SESSION
session_start();

// STORING A SESSION
if(isset($_SESSION['views'])) {
    $_SESSION['views']=$_SESSION['views']+1;
    $_SESSION['age']=20;
    $_SESSION['name']="Nathan";
}
else {
    $_SESSION['views']=1;
    $_SESSION['age']=23;
    $_SESSION['name']="Nanthan";
}

// RETRIEVING A SESSION
echo "Views=". $_SESSION['views'] . "<br>";
echo "Name=". $_SESSION['name'] . "<br>";
echo "Ages=". $_SESSION['age'] . "<br>";

// DESTROYING A SESSION
session_destroy();
?>

Cookie

Creating a cookie
<?php
$expire=time()+60*60*24*30;
setcookie("user", "Alex Porter", $expire);
?>

Handling a cookie
<?php
    if (isset($_COOKIE["user"]))
echo "Welcome " . $_COOKIE["user"] . "!<br />";
    else
        echo "Welcome guest!<br />";
?>

Deleting a cookie
<?php
    setcookie("user", "", time()-$expire); //setting a past time
?>

Smart Glass

 

 

 







Accessing MySql Database

Here System is the mysql database name and table name is Administrator

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import modalclasses.Administrator; //user defined class

public class DBHandler {

    private Connection con;
    private Statement st;
    private ResultSet rs;
    private PreparedStatement ps;

    public Connection getMySqlConnection() throws ClassNotFoundException, SQLException {
        Class.forName("com.mysql.jdbc.Driver");
        String url = "jdbc:mysql://localhost:3306/mysql";
        return DriverManager.getConnection(url, "root", "");
    }

    public void addAdmin(Administrator a) throws SQLException, ClassNotFoundException {
        con = getMySqlConnection();
        ps = con.prepareStatement("insert into System.Administrator values(?,?,?,?,?)");
        ps.setString(1, a.getUserName());
        ps.setString(2, String.valueOf(a.getPassword()));
        ps.setString(3, a.getName());
        ps.setString(4, a.getGender());
        ps.setString(5, a.getEmail());
        ps.executeUpdate();
        con.close();
    }

    public Administrator getAdminDetails(String uname) throws ClassNotFoundException, SQLException {
        con = getMySqlConnection();
        st = con.createStatement();
        rs = st.executeQuery("select * from System.Administrator where Username='" + uname + "'");
        if (!(rs.next())) //if Admin is not found
        {
            return null;
        } else {
            return new Administrator(uname,rs.getString("Password"),rs.getString("Name"),rs.getString("Gender"),rs.getString("Email"));
        }
    }

    public void updateAdmin(Administrator a, String uname) throws ClassNotFoundException, SQLException {
        con = getMySqlConnection();
        ps = con.prepareStatement("update System.Administrator set Username=?,Password=?,Name=?,Gender=?,Email=?" + "where Username='" + uname + "'");
        ps.setString(1, a.getUserName());
        ps.setString(2, String.valueOf(a.getPassword()));
        ps.setString(3, a.getName());
        ps.setString(4, a.getGender());
        ps.setString(5, a.getEmail());
        ps.executeUpdate();
        con.close();
    }

    public void deleteAdmin(String uname) throws ClassNotFoundException, SQLException {
        con = getMySqlConnection();
        ps = con.prepareStatement("delete from System.Administrator where Username='" + uname + "'");
        ps.executeUpdate();
        con.close();
    }
}

TCP Server-Client Application

Server Application

import java.io.*;
import java.net.*;

public class TCPServer{
public static void main(String args[]){
int port=8088;
ServerSocket ser1=null;
PrintWriter pr=null;
BufferedReader br=null;
String str;
Socket soc1=null;

try{
ser1=new ServerSocket(port);
}catch(IOException e){
System.exit(0);
}
while(true){
try{
soc1=ser1.accept();     
        pr=new PrintWriter(new OutputStreamWriter(soc1.getOutputStream()));
pr.println("Client is connected");
        br=new BufferedReader(new InputStreamReader(soc1.getInputStream()));

while((str=br.readLine()) != null)
   System.out.println(str);

if(soc1!=null){
pr.close();
soc1.close();                
}
}catch(IOException e) {
System.out.println(e);
}
}
}
}

Client Application

import java.io.*;
import java.net.*;

public class TCPClient{
public static void main(String args[]){

Socket soc1;
BufferedReader br;
String str;
PrintWriter pr=null;
try{
soc1=new Socket("127.0.0.1",8088);        
        br=new BufferedReader(new InputStreamReader(soc1.getInputStream()));

while((str=br.readLine()) != null)
   System.out.println(str);
        
        pr=new PrintWriter(new OutputStreamWriter(soc1.getOutputStream()));
pr.println("Server is connected");

br.close();
soc1.close();
pr.close();
}catch(ConnectException e){
 System.out.println(e);
}catch(IOException e){
System.out.println(e);
}       
}
}

Analog to Digital Conversion in PIC18F Series

This program converts the Analog voltage signal from the photentiometer of the development board and convert in to digital. This value is then devide by 4 and result is shown in the PORTB LEDS. Turn the Photentiomter to see the LED variation.

#include <stdio.h>
#include <P18CXXX.h>    
#include <adc.h>
#include <timers.h>
 
#pragma code page  // This code make sure the program starts from 0x0004, not from 0x0000

void OpenADC( unsigned char config,unsigned char config2 );  // prototypes
void ConvertADC( void );
void OpenTimer2( unsigned char config );
void OpenPWM1( char period );
void OpenPWM2( char period );
void SetDCPWM1( unsigned int dutycycle );
void SetDCPWM2( unsigned int dutycycle );

int data; // global variables goes to here

void delay (void) // user define delay function
{
long i,C;
for (i=0;i<30000;i++)
C = C+1;
}
void main (void) // main  function 
{
TRISB = 0; // Port,pin direction configuration
PORTB = 0;
TRISC = 0;
PORTC = 0;
TRISCbits.TRISC7 = 1;  // make sure this pin is input

OpenADC (ADC_FOSC_32 & ADC_RIGHT_JUST & ADC_5ANA_0REF, ADC_CH4 & ADC_INT_OFF );  // init ADC
OpenPWM1(0xff); // int PWM1
OpenPWM2(0xff); // int PWM1
OpenTimer2 ( TIMER_INT_OFF & T2_PS_1_16 & T2_POST_1_8 ); // int Timer2
while (1)     // this is how to make a never ending loop.
{
ConvertADC();
while( BusyADC() ); // Wait for AtoD complete.
data = ReadADC();

PORTB = data/4; // Put the AtoD value in to the PortB by deviding ADC value by 4

PORTCbits.RC0 = 1; // Set motor 1 direction
PORTCbits.RC3 = 0;

PORTCbits.RC5 = 1;  // Set motor 2 direction
PORTCbits.RC4 = 0;

SetDCPWM2(data); // Set duty cycle value for PWM2
SetDCPWM1(data); // Set duty cycle value for PWM1

delay();
}
}

CNC Milling Machines

Introduction

Milling is the process of machining flat, curved, or irregular surfaces by feeding the work piece against a rotating cutter containing a number of cutting edges. The milling machine consists basically of a motor driven spindle, which mounts and revolves the milling cutter, and a reciprocating adjustable worktable, which mounts and feeds the work piece. Milling machines may be manually operated, mechanically automated, or digitally automated via Computer Numerical Control (CNC). The CNC milling machine is used to manufacture high precision quality components in large volume. CNC machines are also used for polishing welded area and for various fine tuning and finishing applications.

Classification and Advantages

Milling machines are broadly classified as vertical or horizontal according to the orientation of the spindle axis.

v  Vertical CNC Milling Machine and the Vertical Machining Centre (VMC)
They are probably the most common CNC machine tools found today and can be easily adapted to a great variety of work pieces. Vertical CNC milling machines are easy to load and their operators have good visibility of cutting zone. VMCs are usually considered as good, all purpose of machine tools but, they are not as heavy duty as HMCs. Removing chips is difficult, as they tend to fall back into the cutting zone. VMCs are typically made in a bed-type construction, whereas vertical CNC milling machine uses the knee and column construction.

v  Horizontal CNC Milling Machine and the Horizontal Machining Centre (HMC)
HMC is similar in construction to the conventional horizontal milling machine. However Conventional horizontal mills commonly use cutting tool that are mounted to an arbour. HMCs usually use spindle-mounted cutting tools in the same way as VMC. In fact, an HMC is basically a VMC that has been tipped over.
There are some advantages to HMC construction and configuration. First the spindle is mounted to a stationary and extremely rigid base. This rigid construction allows heavy cutting and high material removal rates. Next the tool and the work piece are mounted horizontally. When we remove lot of material, we will produce lot of chips. If they get stuck in the cutting zone can ruin the work piece and destroy the cutting tools. The horizontal configuration allows gravity to help remove the chips. The disadvantage of HMCs is the work piece is often mounted horizontally on a tombstone. It tends to be more difficult for the operator to hold and align heavy work pieces while fighting gravity and it will be difficult for the operator to see the tool and cutting zone.

Some Other Classifications

v  No of Axes (2,3,4 or more up to 9)
The ways of tool movements refers to axes. Multi axes machines offer several improvements over other CNC tools as follows; Amount of work is reduced, better surface finish can be obtained by moving the tool tangentially about the surface and more complex parts can be manufactured, particularly parts with curved holes.
v  Knee and Column Type
These tend to be fairly small and have a movable quill and used for general purpose milling operations.
v  Bed Type
Bed-type construction is suitable for larger machines. They most often use a solidly mounted spindle rather than a quill. These machines have high stiffness and are used for high production work.
v  Planer Machines
They are similar to bed type but are equipped with several cutters and heads to mill various surfaces.
v  Rotary Table Machines
These are similar to vertical mills and are equipped with one or more heads to do face milling operations.
v  Pallet Changing Type
The advantage of pallet system is that while the machine is machining one work piece, the operator can be setting up the next work piece on an identical fixture on the other pallet. This can reduce amount of down time, when the machine is not making chips.

Thursday, December 9, 2010

Multivibrator

Introduction

A multivibrator is an electronic circuit used to implement a variety of simple two-state systems such as oscillators, timers and flip-flops. It is characterized by two amplifying devices (transistors, electron tubes or other devices) cross-coupled by resistors and capacitors. According to the no of stable states it can be categorized into following three types;
  • Monostable multivibrator
  • Bistable multivibrator
  • Astable multivibrator


Simplest multivibrator circuit consists of two cross coupled transistors and suitable resistors and capacitors are used to define the time periods of the unstable states and various above types can be implemented. This simplest form tends to be inaccurate since many factors affect their timing, so they are rarely used where very high precision is required. Therefore when we need high precision we need to go for digital gate networks or integrated timer circuits.

Multivibrators find applications in a variety of systems where square waves or timed intervals are required. For example sequential logic circuits can be used to build more complex circuits such as counters, shift registers, latches or memories, synchronized circuits etc, but for these types of circuits to operate in a sequential way, they require the addition of a clock pulse or timing signal to cause them to change their state; this clock pulses can be generated by multivibrator circuits.

Monostable Multivibrator
Using BJT

Using NAND gates
Using 555 Timer IC

Bistable Multivibrator

Using BJT

Using NAND gates
Using 555 Timer IC
Astable Multivibrator
Using BJT

Using NAND gates

Using 555 Timer IC

Wednesday, December 8, 2010

Generic Binary Search Tree

Tree Node
public class TreeNode<T extends Comparable<T>> {
    TreeNode<T> leftNode;
    TreeNode<T> rightNode;
    T data;
    public TreeNode(T nodeData) {
        data = nodeData;
        leftNode = rightNode = null;
    }
    public void insert(T insertValue) {
        if (insertValue.compareTo(data) < 0) {
            if (leftNode == null) {
                leftNode = new TreeNode<T>(insertValue);
            } else {
                leftNode.insert(insertValue);
            }
        }else if (insertValue.compareTo(data) > 0) {
            if (rightNode == null) {
                rightNode = new TreeNode<T>(insertValue);
            } else {
                rightNode.insert(insertValue);
            }
        }
    }
}

Binary Search Tree

public class Tree<T extends Comparable<T>>      {
    private TreeNode<T> root;
    public Tree() {
        root = null;
    }
    public void insertNode(T insertValue) {
        if (root == null) {
            root = new TreeNode<T>(insertValue);
        } else {
            root.insert(insertValue);
        }
    }
    public void preOrderTraversal() {
        preOrderHelper(root);
    }
    private void preOrderHelper(TreeNode<T> node) {
        if (node == null) {
            return;
        }
        System.out.print(node.data + " ");
        preOrderHelper(node.leftNode);
        preOrderHelper(node.rightNode);
    }
    public void inOrderTraversal() {
        inOrderHelper(root);
    }
    private void inOrderHelper(TreeNode<T> node) {
        if (node == null) {
            return;
        }
        inOrderHelper(node.leftNode);
        System.out.print(node.data + " ");
        inOrderHelper(node.rightNode);
    }
    public void postOrderTraversal() {
        postOrderHelper(root);
    }
    private void postOrderHelper(TreeNode<T> node) {
        if (node == null) {
            return;
        }
        postOrderHelper(node.leftNode);
        postOrderHelper(node.rightNode);
        System.out.print(node.data + " ");
    }
}