Wednesday, November 4, 2015

Simple Elevator simulation using 8051 micro controller and multisim

Have wonder any time how elevator works and keeps track of all the user interactions like key presses from inside the elevator and the key presses from the outside world. If your answer is yes this series of posts are for you.

Let start with very simple elevator which operates between two stairs. consider ground and first.
The basic ideology behind this elevator is only two switches are available outside and no switch is available. When the simulation starts the elevator is in ground floor.

The moment of the elevator depends on the switches available outside the elevator. The elevator is simulated with two bar led graphs. Ground floor is simulated using green color led graph and first stair is represented with red led bar graph.

when the switch one is open the micro controller receives the voltage and assumes the elevator has to go to ground floor. When the switch two is open the micro controller receives the voltage on second pin of the second port assuming elevator has to go for first stair.

The circuit is very basic so the switch has to be open till the elevator reaches the desired stair. when the simulation starts the elevator is in ground floor and the switches are closed representing the zero energy state.

once the simulation starts the user can play with the switches to simulate the elevator behavior.

If you closely observes the circuit you can observe one problem the switches are the simple switches they will stay in that position once the user presses them. The user has to reset the switch to the original position once the elevator reaches him/her.


The circuit is not designed to handle the interrupts. In next post I will explain how this simple circuit can be modified further to handle the more complex behavior. You can observe the circuit simulation in video.

Below is the code snippet used to program the mcu

#include <regx52.h>

#define floor0 P2_0
#define floor1 P2_1

void main ()
{
unsigned int pressed[2]; 
unsigned int i = 0;
P3 = 0xFF;
P1 = 0x00;
while(1)
{
for(i ; i< 50;i++);
if (floor0)
{
pressed[0] = 1;
}
else
{
pressed[0] = 0;
}
if (floor1)
{
pressed[1] = 1;
}
else
{
pressed[1] = 0;
}
if (pressed[1] == 1)
{
for(i= 0;i<10;i++);
P3_7 = 0;
P1_7 = 1;
for(i = 0;i<100;i++);
P3_6 = 0;
P1_6 = 1;
for(i = 0;i<100;i++);
P3_5 = 0;
P1_5 = 1;
for(i = 0;i<100;i++);
P3_4 = 0;
P1_4 = 1;
for(i = 0;i<100;i++);
P3_3 = 0;
P1_3 = 1;
for(i = 0;i<100;i++);
P3_2 = 0;
P1_2 = 1;
for(i = 0;i<100;i++);
P3_1 = 0;
P1_1 = 1;
for(i = 0;i<100;i++);
P3_0 = 0;
P1_0 = 1;
}
if (pressed[0] == 1)
{
P1_0 = 0;
P3_0 = 1;
for(i;i<100;i++);
P1_1 = 0;
P3_1 = 1;
for(i = 0;i<100;i++);
P1_2 = 0;
P3_2 = 1;
for(i = 0;i<100;i++);
P1_3 = 0;
P3_3 = 1;
for(i = 0;i<100;i++);
P1_4 = 0;
P3_4 = 1;
for(i = 0;i<100;i++);
P1_5 = 0;
P3_5 = 1;
for(i = 0;i<100;i++);
P1_6 = 0;
P3_6 = 1;
for(i = 0;i<100;i++);
P1_7 = 0;
P3_7 = 1;
}
}
}



Sunday, October 11, 2015

Load Image on Java GUI using Open CV

Finally Open CV has support for desktop java. We can directly use this feature to do so many interesting image processing applications. We can head start with trivial application loading the image on jframe using Open CV.

Create small GUI with the menu bar. Add the action for the menu clicks. Instantiate file chooser in java to enable the user to browse the image file. So that the GUI looks like as below


Once the View Image menu is clicked the image must load. divide this task into simple tasks
1. Get the image path as below
fc.getSelectedFile().getAbsolutePath()
2. Read the image data from disc as below
Mat m = Imgcodecs.imread("image location");
3. Resize the large images so that it's new size will match with the component on the jframe.
Imgproc.resize(m, dest, new Size(label.getWidth(),label.getHeight()));
4. Convert the Open CV Mat data structure to the Java Buffered Image type so that we can directly load this image on the jlabel as below

int type = BufferedImage.TYPE_BYTE_GRAY;
      if ( m.channels() > 1 )
      {
          type = BufferedImage.TYPE_3BYTE_BGR;
      }
      int bufferSize = m.channels()*m.cols()*m.rows();
      byte [] b = new byte[bufferSize];
      m.get(0,0,b); // get all the pixels
      BufferedImage image = new BufferedImage(m.cols(),m.rows(), type);
      final byte[] targetPixels = ((DataBufferByte) image.getRaster().getDataBuffer()).getData();
      System.arraycopy(b, 0, targetPixels, 0, b.length);
      return image;

5. load the returned image on jlabel




Monday, August 31, 2015

Quadrants of a matrix in Matlab

Intention of the program is to take the scalar as the argument names n and to return the matrix of size 2nx2n. Such that the elements of the matrix will be like The elements of the submatrix in the top left corner are all 1s the elements of the submatrix at the top right are 2s the elements in the bottom left are 3s and the elements in the bottom right are 4s.

function [Q] = quadrants(n)
Q = [ones(n) ones(n)+1 ; ones(n)+2 ones(n)+3];
end

Monday, August 10, 2015

How much time robot will take to fell in ditch

A robot is programmed to move forward F meters and backwards again, say B meters, in a straight line. The Robot covers 1 meter in T units of time. On Robot's path there is a ditch at a distance FD from initial position in forward direction as well as a ditch at a distance BD from initial position in backward direction. This forward and backward movement is performed repeatedly by the Robot.
Input Format:

First line contains total number of test cases, denoted by N
Next N lines, contain a tuple containing 5 values delimited by space
F B T FD BD, where

  1. F denotes forward displacement in meters
  2. B denotes backward displacement in meters
  3. T denotes time taken to cover 1 meter
  4. FD denotes distance from Robot's starting position and the ditch in forward direction
  5. BD denotes distance from Robot's starting position and the ditch in backward direction

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

public class Catch22
{
    public static void main(String[] args) throws FileNotFoundException, IOException
    {
        BufferedReader br;
        br = new BufferedReader(new FileReader(args[0]));
        String line;
        int loc = 0 ,numOfTestCases = 0;
        int F,B,T,FD,BD,distanceFromCenter , totalDistanceCovered;
        while( ( line = br.readLine()) != null )
        {
            distanceFromCenter = 0;
            totalDistanceCovered = 0;
            ++loc;
            if ( loc > (numOfTestCases+1))
            {
                break;
            }
            else if ( loc == 1)
            {
                numOfTestCases = Integer.parseInt(line.trim());
                continue;
            }
            String[] tokens = line.trim().split("\\s+");
            F = Integer.parseInt(tokens[0].trim());
            B = Integer.parseInt(tokens[1].trim());
            T = Integer.parseInt(tokens[2].trim());
            FD = Integer.parseInt(tokens[3].trim());
            BD = Integer.parseInt(tokens[4].trim());
            if ( ( F == B) && ( F < FD) )
            {
                System.out.println("No Ditch");
                continue;
            }
            else
            {
                distanceFromCenter = F;
                totalDistanceCovered = F;
                while (true)
                {
                    if ( distanceFromCenter >= FD)
                    {
                        int time = (totalDistanceCovered+(FD-distanceFromCenter)) * T;
                        System.out.println(time+" F");
                        break;
                    }
                    distanceFromCenter = distanceFromCenter - B;
                    totalDistanceCovered = totalDistanceCovered + B;
                    if ( distanceFromCenter < 0 )
                    {
                        if ( (-1*distanceFromCenter) >= BD)
                        {
                            int time = (totalDistanceCovered+(BD-(-1*distanceFromCenter))) * T;
                            System.out.println(time+" B");
                            break;
                        }
                    }
                    distanceFromCenter = distanceFromCenter + F;
                    totalDistanceCovered = totalDistanceCovered + F;
                }
            }
        }
    }
}

Sunday, August 2, 2015

Mtable using matlab

function [mt , s] = mtable( n , m)
mt = zeros(n,m);
for c = 1 : m
    for r = 1 : n
        mt(r,c) = c*r;
    end
end
s = sum(sum(mt));
end

Identity using matlab

function [Q] = identity(n)
Q = zeros(n,n);
for c = 1 : n
    for r = 1 : n
        if c == r
            Q(r,c) = 1;
        end
    end
end
end

Checkerboard using matlab

function [ Q ] = checkerboard( n , m )
Q = ones(n,m);
for c = 1 : m
    for r = 1 : n
        if mod(r,2) == 0 && ~mod(c,2) == 0
            Q (r,c) = 0;
        elseif ~mod(r,2) == 0 && mod(c,2) == 0
            Q (r,c) = 0;
        end
    end
end
end

Randomness using matlab

function [Q] = randomness (limit , n , m )
Q = 1 + floor(rand(n,m)*limit);
end

Quadrants using matlab

function [Q] = quadrants(n)
Q = [ones(n) ones(n)+1 ; ones(n)+2 ones(n)+3];
end

Saturday, April 25, 2015

Prime numbers in a range given by user in C Language


#include <conio.h>

int main(int argc, char* argv[])
{
    int start = 0 , end = 0 ;
    printf("Enter the starting number in range");
    scanf_s("%d",&start);
    printf("Enter the ending number in range");
    scanf_s("%d",&end);
    for (int i = start; i < end ; i++)
    {
        int count = 0;
        for(int j = 1 ; j <= i ; j++)
        {
            if ( i % j == 0 )
            {
                count++;
                if ( count > 2)
                {
                    break;
                }
            }
        }
        if ( count <= 2 )
        {
            printf("%d\n",i);
        }
    }
    getch();
    return 0;
}

Saturday, April 18, 2015

Binary search implememtation in C Language

In previous post we have seen how we can search the list by using simple loop and process is called sequential search. This is useful when we have small lists. But in real world we encounter large lists having thousands or even millions of elements(data).

Iterating over such a large list using simple loop is inefficient in terms of time. Considering the large list having sorted elements we can employ binary search. Generally when storing the data itself if we stored them in sorted order makes our life simple at later part of time when we are retrieving data.

If you observe the name of search algorithm "Binary Search". It conveys we have two parts(Binary). The part of the list having the desired data and the part does not having the desired data.

The c code which explains the binary search is as follows:

int binarySearch(int* array, int size, int reqNum, bool *result )
{
    int startIdx;
    int endIdx;
    int midIdx;
   
    startIdx = 0;
    endIdx = size;
   
    while ( startIdx <= endIdx)
    {
        midIdx = ( startIdx + endIdx ) / 2 ;
        if (reqNum > array[midIdx])
        {
            startIdx = midIdx + 1;
        }
        else if (reqNum < array[midIdx])
        {
            endIdx = midIdx - 1;
        }
        else
        {
            startIdx = endIdx + 1;
        }
    }
    *result = ( reqNum == array[midIdx]);
    return midIdx+1;
}

The logic returns the position of the desired elements in the list. But if we dose not have the required data in the list then also the algorithm returns the 1. but before that we are comparing if the required number is present at the array[midIdx] if the number does not there we are passing the failure as the pointer to the calling function. By using that the calling function can determine weather the data is present in the list are not.

the calling function can be coded as

int main ()
{
    int a[10] = {1,2,120, 240, 256, 300,312, 440, 456, 512};
    bool result;
    int index = binarySearch(a,10, 0, &result );
    if (result)
    {
        printf("Required Number Present at %d position",index );
    }
    else
    {
        printf("Target not found");
    }
}

DC motor control with Pulse Width Modulation Part 1

DC Motor intro DC motor is a device which converts electrical energy into kinetic energy. It converts the DC power into movement. The typica...