2010. 3. 24.

Force of Gravity - Maple



Using a Maple, simulated a system with three masses and their movement, caused by gravitational forces in 3D space. Two bodies are attracted by a force with a magnitude G x m1 x m2 / r^2 (Newton's Law of Universal Gravitation), where G is the gravitational constant, m1 and m2 are masses of two bodies, and r is the distance between the two. The direction of the force is along the line segment joining two bodies. By equating the equation with Newton's second law (F = ma), we can calculate the acceleration (a) of the body, which is equal to second order derivative of the position of the mass. By solving the deferential equation, we can calculate the position of the bodies at a given time, and plot them in 3 dimensional space. The above figure is generated by running the following maple commands (in red). We can also animate the result by running additional commands in blue at the end.



> d3 := proc(i,j) ((x[i](t)-x[j](t))^2 + (y[i](t)-y[j](t))^2 + (z[i](t)-z[j](t))^2)^(1/2) end:
> v3 := [x,y,z]:
> v3[2][1](t):
> N := 3:
> iN := [seq(i,i=1..N)]:

> cde := 0:
     for i to N do 
        i3m := subsop(i=NULL,iN);
        for k to 3 do
           cde := cde+1;
           de[cde] := m[i]*diff(v3[k][i](t),t$2) = add(G*m[i]*m[j]/d3(i,j)^2 * (v3[k][j](t)-v3[k][i](t))/d3(i,j),j=i3m);
        od;
     od:
for i to cde do de[i]; od:

des := convert(de,set):
ic[1] := x[1](0)=0:
ic[2] := y[1](0)=0:
ic[3] := z[1](0)=0.5:
ic[4] := x[2](0)=5:
ic[5] := y[2](0)=0:
ic[6] := z[2](0)=0:
ic[7] := x[3](0)=-2:
ic[8] := y[3](0)=0:
ic[9] := z[3](0)=0:
ic[10] := D(x[1])(0)=.5:
ic[11] := D(y[1])(0)=0:
ic[12] := D(z[1])(0)=0:
ic[13] := D(x[2])(0)=0:
ic[14] := D(y[2])(0)=.4:
ic[15] := D(z[2])(0)=0:
ic[16] := D(x[3])(0)=0:
ic[17] := D(y[3])(0)=-0.16:
ic[18] := D(z[3])(0)=0:
pars := [m[1]=.1,m[2]=3,m[3]=5,G=1]:

ics := convert(ic,set):
va := [seq(seq(v3[i][j](t),i=1..N),j=1..3)]:
ds := dsolve(subs(pars,des) union ics,va,numeric):
pt[0] := ds(0):
n := 1600:
for i to n do pt[i] := ds(i*.05); od:
orb1 := [seq(subs(pt[i],[x[1](t),y[1](t),z[1](t)]),i=0..n)]:
> p1 := plots[pointplot3d](orb1,connect=true,symbol=point,colour=red):

> orb2 := [seq(subs(pt[i],[x[2](t),y[2](t),z[2](t)]),i=0..n)]:
> p2 := plots[pointplot3d](orb2,connect=true,symbol=point,colour=blue):


> orb3 := [seq(subs(pt[i],[x[3](t),y[3](t),z[3](t)]),i=0..n)]:
> p3 := plots[pointplot3d](orb3,connect=true,symbol=point,colour=green):
> plots[display3d]({p1,p2,p3},scaling=constrained,axes=none);





> re := COLOUR(RGB,1.,0.,0.):
> bl := COLOUR(RGB,0.,0.,1.):
> gr := COLOUR(RGB,0.,1.,0.):
> cir := SYMBOL(CIRCLE):
> for i from 0 to n do
     pti := pt[i];
> fr[i] := [POINTS(subs(pti,[x[1](t),y[1](t),z[1](t)]),cir,re),
           POINTS(subs(pti,[x[2](t),y[2](t),z[2](t)]),cir,bl),
           POINTS(subs(pti,[x[3](t),y[3](t),z[3](t)]),cir,gr),
           TITLE(cat("t=",sprintf("%05.2f",subs(pti,t))))];
> od:
> n:fr[n]:
> sc := SCALING(CONSTRAINED):
> an := ANIMATE(seq(fr[i],i=0..n)):
> ax := AXESSTYLE(NONE):
> pa := PLOT3D(an,sc,ax):
> pa;





License Plate Recognition (LPR) System





Implemented a License Plate Recognition (LPR) System for automated garage door opener in C++. When metal detector detects a vehicle approaching to a garage door, the microcontroller sends a signal to the camera to take a snap shot of the vehicle, and the program recognises the license plate from the image, and verifies whether the vehicle is registered or not. The system uses OpenCV (Open Source Computer Vision) Library for image processing. The following code is written to reduce noise, when the system is trying to locate the license plate from the image. An 8 x 8 mask will move from upper-left corner to bottom-right corner linearly, and sum up the values within the mask. If the sum is less than threshold value, the system will assume the area is a noise and removes it from the image.



int noiseFilter(IplImage* inputImage) {
  int i, j, x, y;
       double sum;
   int height = inputImage->height;
  int width = inputImage->width;
  int size = 8;
  for (j = 0; j < height - size; j++) {
for (i = 0; i < width - size; i++ ) {
  sum = 0;
  for (x = 0; x < size; x++) {
  sum += cvGet2D(inputImage, j + 0, i + x ).val[0];
                              sum += cvGet2D(inputImage, j + size -1, i + x).val[0];
                      }
  for (y = 0; y < size; y++) {
  sum += cvGet2D(inputImage, j + y, i + 0 ).val[0];
  sum += cvGet2D(inputImage, j + y, i + size - 1).val[0];
                       }
  if(sum <= 0) {
  for (y = j; y < j + size; y++) {
  for (x = i; x < i + size; x++) {
                  cvSet2D(inputImage, y, x, cvScalar(0,0,0,0));
  }
}
}
}
}
   return 0;
}

Nippon Telegraph and Telephone Corporation (NTT)


Nippon Telegraph and Telephone (NTT) Corporation of Japan is the largest communication company in the world, followed by AT&T. As a Distributed data processing middleware developer, I was responsible for  implementing distributed database with remote-machine-processing capability in Java language. Using various sensors as a source, the system stores data into a hashtable using a unique hash, and upon request from end-point user, the system retrieves the data accordingly. The system can also add, modify and delete the data by the end-point-user. The system is primarily used by researchers to improve the processing time of the database.

4 Degree-of-Freedom SCARA Robot arm simulation





A controller system was written in C++ language, and was implemented on actual system to be tested. A program was able to move the robot to a specified location with a specified velocity unless the location was outside the reachable area. Using a feedback control system, the program controls the forces and torques on the joint motors precisely in stable state. Also, given few points it was able to plan a trajectory, which goes through the specified points.

Real Time Embedded Programming

This is a XModem Protocol written in C++ using QNX Neutrino Operating System Simulator. It sends a file to another location over a network connection, by sending file blocks. Sender and Receiver communicates in real time to ensure correct behaviour of the protocol. The following block of the code opens up two channels for communication, creates 4 threads and establish connection between them. "ackmed" and "sendmed" are "mediums" in-between sender and receiver. "ackmed" sends "acknowledged" from receiver to sender when it is ready to receive the next block. "sendmed" sends file block from sender to receiver upon receiving "acknowledged".



#include <cstdlib>
#include <iostream>
#include <pthread.h>
#include <sys/neutrino.h>

int channelSender;    //Channel for Sender
int channelReceiver;  //Channel for Receiver

void* SenderProc(void *param);
void* ReceiverProc(void *param);
void* KindSendMedium (void *param);
void* KindAckMedia(void *param);

int main(int argc, char *argv[]) {
//std::cout << "Welcome to the Momentics IDE" << std::endl;
pthread_t sender, receiver, kindsendmed, kindackmed;
pthread_attr_t attr;
//Initialize channels
channelSender = ChannelCreate(0);
channelReceiver = ChannelCreate(0);

//Create 4 threads
pthread_attr_init( &attr );
pthread_create( &sender, &attr, &SenderProc, (void *)"XMODEM-Clarified.txt" );
pthread_create( &receiver, &attr, &ReceiverProc, (void *)"XMODEM-Output.dat" );
pthread_create( &kindsendmed, &attr, &KindSendMedium, NULL );
pthread_create( &kindackmed, &attr, &KindAckMedia, NULL );
//Waiting for transmision to be over
pthread_join(sender, NULL);
pthread_join(receiver, NULL);
//The other two threads die out upon exit
//pthread_join(kindsendmed, NULL);
//pthread_join(kindackmed, NULL);
//Destroy channels
ChannelDestroy(channelSender);
ChannelDestroy(channelReceiver);
return EXIT_SUCCESS;
}

Data Structures

I also have written few programs using a data structures, including linked lists, hash tables, priority queues, and binary search trees. The following code is a portion of a rental car management software written in C++. Specifically, it searches a given car class object in the search tree using recursion. Class 'car' is structured as the following:


struct car{
string marque; // -- brand 
string model; // -- model
bool isRented; // -- flag of whether the car is rented
bool reCommissioned; // -- flag of whether the car is reCommissioned (ready to be rented again)
bool inService; // -- flag of whether the car is in service.
car * left; // -- points at the left child
car * right; // -- points at the right child

};




// Search for CarToBeSearched in the tree recursively.
carBST::car* carBST::Search(car* CarToBeSearched, car* node) {

// CarToBeSearched is found!
if(CarToBeSearched->model.compare(node->model) == 0) {
return node;

// CarToBeSearched is smaller than current node.
// continue searching in left subtree
} else if (CarToBeSearched->model.compare(node->model) < 0) {
if (node->left != NULL) {
return Search(CarToBeSearched, node->left);
}

// CarToBeSearched is greater than current node.
// continue searching in right subtree
} else if (CarToBeSearched->model.compare(node->model) > 0) {
if (node->right != NULL) {
return Search(CarToBeSearched, node->right);
}
}

//CarToBeSearched is not found in the tree.
return NULL;
}

Broadcom

(c) Broadcom Corporation


During the summer and fall of 2006, I worked at Broadcom corporation. It headquarters at Irvine, CA, and has many branches worldwide. The VoIP research department that I was working is in the city of Richmond, BC.


As a Quality Assurance Tester / Test Developer, I have written various test scripts in Tcl and Perl scripting languages for Broadcom's wireless VoIP phone - "OnePhone". I was also responsible for finding errors in the firmware, and help developers to fix them. The tests done on the device include simple call answering, call forwarding, redialling, and call waiting, as well as a voice quality test for various codecs, security test, and network test.

Stopwatch on M68H12 Microcontroller



(c) Simon Fraser University, School of Engineering Science




Using a Motorola M68HC12 microcontroller, our team developed a stopwatch in assembly language. It was able to measure time with 1/100 sec accuracy, and display on LCD panel. The project was successful, except debounce issue. We needed a little more memory to implement them on the chip. The following code is a portion of LDC library we have written.





; Subroutine to read from LCD register 0 (Busy flag and address counter).  
; The value read is returned in reg A.
LcdR0Read:
bclr PORTB,LcdRS_DnI | LcdE
bset PORTB,LcdRnW


LcdRead:
bset PORTB,LcdE
nop ; data output 160 ns after rising edge of E
ldaa PORTA
bclr PORTB,LcdE
rts


; Subroutine which waits for the LCD to stop being busy.
; Regs Mod:  CCR (A modified by LcdR0Read)
WaitDone:
bsr LcdR0Read
bita #LcdBusy
bne WaitDone
rts


; Subroutine to perform an instruction.  It waits for the LCD to stop
; being busy before writing the instruction.
; Regs Mod:  A, CCR (A modified by nested subroutine calls)
LcdDoInst:
bsr WaitDone


; Subroutine to write an instruction to the LCD.
; Regs Mod:  CCR
LcdInstWrite:
bclr PORTB,LcdRnW | LcdRS_DnI | LcdE 
bra LcdWrite

File Manager

The following code is a file manager, written in the same course, which can create, append, print and copy a text file. It also can search for a string within the specified file.




import java.io.*;


public class FileMgr{
   // We use a global variable for reading from the 
   // keyboard, since all methods take user input.
   private static BufferedReader kb ; 
   public static void main( String [] args ) throws IOException {
      String kb_line ;       // user input
      char task ;            // task selected 


      // Open Keyboard for User Input
      kb = new BufferedReader(new InputStreamReader( System.in ));
      //Display Welcome Message
      System.out.println("\n================");
      System.out.println("\n  File Manager");
      System.out.println(  "================");
      // User interaction loop.
      do {
         display_menu();                      // Display Menu & Prompt User for Selection
         kb_line = kb.readLine();             // Read Users Response
         if( kb_line == null || kb_line.length() != 1 ) {
            task = '0';                       // denotes (some kinds of) invalid input
         } else {
            // Take First Character of Response (in lower case)
            task = Character.toLowerCase(kb_line.charAt(0));
         }


         // Execute Corrsponding Task
         execute_task( task );


      } while( task != 'q' && task != 'Q' );
   } // End of main


   /*******************************************************
   *  Execute the selected task
   *
   *  Argment task identifies the task.  It need not
   *   have a value that corresponds to a valid selection.
   *******************************************************/
   private static void execute_task( char t ) throws IOException {
      String userLine ;
      String fileLine ;
      BufferedReader inFile ;
      PrintWriter outFile ;


      switch( t ){


      case 'p':// Print a file


         // open file for printing 
         userLine = get_user_input("\nEnter Name of File to Print\n");
         inFile = open_input_file( userLine );
         System.out.println("=== Begin " + userLine + " ============");


         // print lines to the screen
         fileLine = inFile.readLine();
         while( fileLine != null ) {
            System.out.println( fileLine );
            fileLine = inFile.readLine();
         }
         System.out.println("=== End " + userLine + " ===========");
         inFile.close();
         break;


      case 's':           // Search a file - print lines of file containing 
                          // a given substring.


         // open file to search and get search string
         userLine = get_user_input("\nEnter Name of File to Search\n");
         inFile = open_input_file( userLine );
         userLine =  get_user_input("\nEnter String to Search for\n");


         System.out.print("=== Begin " + userLine + " lines containing ");
         System.out.println( userLine + " ============");


         // print lines containing userLine as a sub-string
         fileLine = inFile.readLine();
         while( fileLine != null ) {
            if( fileLine.indexOf( userLine, 0 ) > -1 ){
               System.out.println( fileLine );
            }
            fileLine = inFile.readLine();
         }
         inFile.close();


         System.out.print("=== End " + userLine + " lines containing ");
         System.out.println( userLine + " ===========");
         break;


      case 'c':                 // Copy a file


         // open files to copy from and to
         userLine = get_user_input("\nEnter Name of File to Copy From\n");
         inFile = open_input_file( userLine );
         userLine = get_user_input("\nEnter Name of File to Copy To\n");
         outFile = new PrintWriter( new FileWriter( userLine, true ));


         // copy lines
         fileLine = inFile.readLine();
         while( fileLine != null ) {
            outFile.println( fileLine );
            fileLine = inFile.readLine();
         }
         inFile.close();
         outFile.close();
         break;


      case 'n':


         // open new file 
         userLine = get_user_input("\nEnter Name of New File\n");
         outFile = new PrintWriter( new FileWriter( userLine ));


         System.out.print("\nBegin entering lines ");
         System.out.println("(stop by entering the line: #!stop).");


         // get lines from user and store in file
         userLine = get_user_input("");
         while( userLine != null && userLine.compareTo("#!stop") != 0 ) {
            outFile.println( userLine );
            userLine = get_user_input("");
         }
         outFile.close();
         break;


      case 'a':            // append to an existing file 


         // open desired file to append to 
         userLine = get_user_input("\nEnter Name of File to Append to\n");
         outFile = new PrintWriter( new FileWriter( userLine, true ));


         System.out.print("\nBegin entering new lines ");
         System.out.println("(Stop by entering the line: #!stop).");


         // read lines from user and store in file
         userLine = get_user_input("");
         while( userLine != null && userLine.compareTo("#!stop") != 0 ){
            outFile.println( userLine );
            userLine = get_user_input("");
         }
         outFile.close();
         break;


      case 'q':            // quit
         System.out.println("Bye!");
         break;


      default:        // handle invalid selections
         System.out.println("Your entry is not a valid selection.");
     }
  }  // End of execute_task()


   /*******************************************************
   *  Prompt the user and read a line from the keyboard.
   *  Returns the String read from the keyboard.       
   *******************************************************/
   private static String get_user_input( String prompt ) throws IOException {
      System.out.print( prompt );
      System.out.print(">>> ");
      return kb.readLine();
   }


   /*******************************************************
   *  Open a file with a given name for reading.
   *  Returns a new BufferedReader
   *******************************************************/
   private static BufferedReader open_input_file(String name) throws IOException {
      return new BufferedReader( new FileReader( name ));
   }


   /*******************************************************
   *  Display the task menu and instructions
   *******************************************************/
   private static void display_menu(){
      System.out.println("\nSelect a task from the following list by");
      System.out.println("type the first letter of the desired task ");
      System.out.println("(upper or lower case) and pressing Enter.");
      System.out.println("\nNew: create a new file");
      System.out.println("Append: append to an existing file");
      System.out.println("Print: print file to the screen");
      System.out.println("Copy: copy a file");
      System.out.println("Search: find a string in a file");
      System.out.println("Info: print program information");
      System.out.println("Quit: exit File Manager");
      System.out.print("\nTask: ");
   }
}  // End of FileMgr