Followers

Tuesday, 2 June 2015

TE-SEM2-PL-3

Assignments Group A (Mandatory)


1]. Develop an application using Beeglebone Black/ ARM Cortex A5 development board to simulate the operations of LIFT.

2]. Develop an application using Beeglebone Black/ ARM Cortex A5 development board to simulate the working of signal lights.

3]. Implement an calculator (64 bit Binary Multiplication) application using concurrent lisp

4]. Apply the Following Software Engineering to all assignments(No 1,2,3 of Group A and B). Mathematical Modeling must result into UML Requirements.
Apply Assignment No 4a to 4d for all Group A and Group B assignments of Embedded Operating system and Concurrent and Distributed Programming. Use tools Open source tools like ArgoUML, UMLLet, StarUML or equivalent tools for UML models) Or Use Agile or Scrum-Agile methodologies and Tools.Use of Possitive and Negative Testing.

5]. Create Project plan, SRS, Design document and Test Plan for one group-C assignment from embedded operating system or Concurrent and Distributed Programming

6]. Write an application to parse input text file concurrently and compare the result of concurrent parsing with serial parsing ( Use concurrent YACC parser)


Assignments Group B (Any Six Assignments, All assignments to be covered in the Batch)


1]. Write an application to and demonstrate the change in BeagleBoard/ ARM Cortex A5 /Microprocessor /CPU frequency or square wave of programmable frequency.

2]. Implement a Parallel Quick Sort algorithm using NVIDIA GPU or equivalent ARM board.

3]. Vedic Mathematics method to find square of 2-digit number is used in a distributed programming. Use shared memory and distributed (multi-CPU) programming to complete the task.

4]. Implement a Parallel ODD-Even Sort algorithm using GPU or ARM equivalent.

5]. Implement n-ary search algorithm using OPENMP

6]. Implement concurrent prims algorithm using OPENMP

7]. Implement nxn matrix parallel multiplication using CUDA/OpenCL GPU, use shared memory.

8]. Develop a network based application by setting IP address on BeagleBoard/ ARM Cortex A5.

9]. Implement a Multi-threading application for echo server using socket programming in JAVA

10]. Implement Reader-Writer problem using OPENMP

11]. Implement a dinning philosophers problem using OpenCL wherein each philosopher is a distributed computer memory in a cluster.

12]. A text file is stored in a distributed manner on three hard disks on three machines such that consecutive lines, one per hard disk are stored in cyclic manner. Write a program using OpenCL to read/Write/Modify the file.

13]. A file holds a data structure that is written and modified by number of users in a distributed manner. Multiple users on multiple computers use Read-Modify-Write cycle provided resource is available else use use modify once before exit. Write necessary Program using OpenCL.

14]. Perform Assignment No 4 of Group A for Assignment No 12 of Group-B using UMLLet

15]. Perform Assignment No 4 of Group A for Assignment No 13 of Group-B usung concurrent UML.


Assignment Group C: Advance Technology Assignments (Any One)


1]. Develop Robotics(stepper motor) Application using Beagle Board.

2]. Develop bus arbitration logic using VME/PCI bus for cluster of CPU boards for high performance computing (BIG DATA)

3]. Implement a Distributed matrix multiplication using CUDA / OpenMPI






**************************************************

 Grp-A 1].

**************************************************


/*==================================================================/// GROUP A
// ASSIGNMENT NO : 1
// Title : Develop an application using Beeglebone Black/ ARM Cortex A5 development board
//             to simulate the operations of LIFT.
// ROLL NO :
// BATCH : T1
// CLASS : TE(computer)
//===================================================================
PROGRAM :

/* Standard C Header Files */
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>

/* Standard C++ Header Files */
#include<iostream>
#include<fstream>
#include<string>
#include<sstream>
#include<csignal>
#include <cstdlib>
//================================================================
/* GPIO PIN definitions for the button press LEDs (RED LEDs on Board) */
#define     LED_1        (0 * 32) + 3        /* GPIO0_3 */
#define     LED_2        (0 * 32) + 23        /* GPIO0_23 */
#define     LED_3        (0 * 32) + 2        /* GPIO0_2 */
#define     LED_4        (0 * 32) + 26        /* GPIO0_26 */

/* GPIO PIN definitions for the lift position LEDs (GREEN LEDs on Board) */
#define     LED_5        (1 * 32) + 17        /* GPIO1_17 */
#define     LED_6        (1 * 32) + 15        /* GPIO1_15 */
#define     LED_7        (0 * 32) + 15        /* GPIO0_15 */
#define     LED_8        (1 * 32) + 14        /* GPIO1_14 */

/* GPIO PIN definitions for the direction LEDs (YELLOW LEDs on Board) */
#define     LED_9        (0 * 32) + 30        /* GPIO0_30 */
#define     LED_10        (2 * 32) + 2        /* GPIO2_2 */
#define     LED_11        (1 * 32) + 28        /* GPIO1_28 */
#define     LED_12        (2 * 32) + 3        /* GPIO2_3 */
#define     LED_13        (0 * 32) + 31        /* GPIO0_31 */
#define     LED_14        (2 * 32) + 5        /* GPIO2_5 */
#define     LED_15        (1 * 32) + 18        /* GPIO1_18 */

/* GPIO PIN definitions for the lift BUTTONs (Buttons on Board) */
#define     SW_1        (0 * 32) + 14        /* GPIO0_14 */
#define     SW_2        (0 * 32) + 27        /* GPIO0_27 */
#define     SW_3        (0 * 32) + 22        /* GPIO0_22 */
#define     SW_4        (2 * 32) + 1        /* GPIO2_1 */

/* LIFT DIRECTION: LEDs to represent lift direction (up or down) */
#define     LIFT_DIR_1            LED_9        /* LD9 */
#define     LIFT_DIR_2            LED_10        /* LD10 */
#define     LIFT_DIR_3            LED_11        /* LD11 */
#define     LIFT_DIR_4            LED_12        /* LD12 */
#define     LIFT_DIR_5            LED_13        /* LD13 */
#define     LIFT_DIR_6            LED_14        /* LD14 */
#define     LIFT_DIR_7            LED_15        /* LD15 */

/* LIFT POSITION: LEDs to indicate the current position of Lift */
#define     LIFT_POS_0            LED_5        /* LD5 */
#define     LIFT_POS_1            LED_6        /* LD6 */
#define     LIFT_POS_2            LED_7        /* LD7 */
#define     LIFT_POS_3            LED_8        /* LD8 */

/* * LIFT BUTTONS: Buttons corresponding to each floor of the Lift * */
#define     LIFT_BUTTON_0        SW_1        /* SW1 */
#define     LIFT_BUTTON_1        SW_2        /* SW2 */
#define     LIFT_BUTTON_2        SW_3        /* SW3 */
#define     LIFT_BUTTON_3        SW_4        /* SW4 */

/* * LIFT LEDS: LEDs to indicate the BUTTON Press on each floor * */
#define     LIFT_LED_0            LED_1        /* LD1 */
#define     LIFT_LED_1            LED_2        /* LD2 */
#define     LIFT_LED_2            LED_3        /* LD3 */
#define     LIFT_LED_3            LED_4        /* LD4 */
//===================================================================
/* * An array of DIRECTION LEDS * */
unsigned int dir_leds[] =
{
        LIFT_DIR_1,
        LIFT_DIR_2,
        LIFT_DIR_3,
        LIFT_DIR_4,
        LIFT_DIR_5,
        LIFT_DIR_6,
        LIFT_DIR_7
};

/* * An array of POSITION LEDS * */
unsigned int pos_leds[] =
{
        LIFT_POS_0,
        LIFT_POS_1,
        LIFT_POS_2,
        LIFT_POS_3
};

/* * An array of lift BUTTONs * */
unsigned int lift_buttons[] =
{
        LIFT_BUTTON_0,
        LIFT_BUTTON_1,
        LIFT_BUTTON_2,
        LIFT_BUTTON_3
};

/* * An array of BUTTON PRESS LEDS * */
unsigned int lift_leds[] =
{
        LIFT_LED_0,
        LIFT_LED_1,
        LIFT_LED_2,
        LIFT_LED_3
};
//===================================================================
#define NO_OF_FLOORS        4       
#define NO_OF_DIR_LEDS        7       
#define DEFAULT_LIFT_POS    0       

struct floor
{
    int fd;                       
    unsigned int button;       
    unsigned int led;           
};

struct  floor floor_set[NO_OF_FLOORS] =
{
        {-1, LIFT_BUTTON_0, LIFT_LED_0},   
        {-1, LIFT_BUTTON_1, LIFT_LED_1},   
        {-1, LIFT_BUTTON_2, LIFT_LED_2},   
        {-1, LIFT_BUTTON_3, LIFT_LED_3}       
};

/* Use std namespace for various C++ definitions */
using namespace std;

/* PATH of a GPIO specific sysfs interface directory on Linux system */
#define SYSFS_GPIO_DIR "/sys/class/gpio"
//=================================================================
void gpioExport(string gpio)
{
       fstream fs;
       string path(SYSFS_GPIO_DIR);                           
       fs.open((path + "/export").c_str(), fstream::out);   
       fs << gpio;                                               fs.close();                                           
}
//===============================================================
void gpioUnexport(string gpio)
{
       fstream fs;                                               string path(SYSFS_GPIO_DIR);                           
       fs.open((path + "/unexport").c_str(), fstream::out);   
       fs << gpio;                                               fs.close();                                           
}
//================================================================
void gpioSetDir(string gpio, string dir)
{
       fstream fs;                                           
       string path(SYSFS_GPIO_DIR);                           
       fs.open((path + "/gpio" + gpio + "/direction").c_str(), fstream::out);
       fs << dir;                                               fs.close();                                           
}
//================================================================
void gpioSetValue(string gpio, string val)
{
       fstream fs;                                               string path(SYSFS_GPIO_DIR);                           
       fs.open((path + "/gpio" + gpio + "/value").c_str(), fstream::out);
       fs << val;                                           
       fs.close();                                           
}
//===============================================================
void gpioSetEdge(string gpio, string edge)
{
       fstream fs;                                               string path(SYSFS_GPIO_DIR);                           
       fs.open((path + "/gpio" + gpio + "/edge").c_str(), fstream::out);
       fs << edge;                                               fs.close();                                           
}
//=================================================================
#define MAX_BUF            1           
char *buf[MAX_BUF];                   
fd_set read_fds;                   
int max_fd;                           
//=================================================================
string to_string(int a)
{
    ostringstream temp;                   
    temp<<a;                           
    return temp.str();                   
}
//================================================================
void liftLEDExit(string liftLED)
{
    gpioSetValue(liftLED, "0");           
    gpioUnexport(liftLED);               
}
//==================================================================
void liftLEDInit(string liftLED)
{
    gpioExport(liftLED);               
    gpioSetDir(liftLED, "out");           
    gpioSetValue(liftLED, "0");           
}
//===============================================================
void liftLEDOn(string liftLED)
{
    gpioSetValue(liftLED, "1");           
}
//=================================================================
void liftLEDOff(string liftLED)
{
    gpioSetValue(liftLED, "0");           
}
//===================================================================
void liftButtonExit(string button)
{
    gpioUnexport(button);               
}
//==================================================================
void liftButtonInit(string button)
{
    gpioExport(button);                   
    gpioSetDir(button, "in");           
    gpioSetEdge(button, "falling");       
}
//=================================================================
void liftInitAll(void)
{
    unsigned char i;                               
    for(i=0; i<NO_OF_DIR_LEDS; i++)                   
            liftLEDInit(to_string(dir_leds[i]));   
    for(i=0; i<NO_OF_FLOORS; i++)                   
    {
        liftLEDInit(to_string(pos_leds[i]));       
        liftLEDInit(to_string(lift_leds[i]));       
        liftButtonInit(to_string(lift_buttons[i]));   
    }
}
//===================================================================
void liftExitAll()
{
    unsigned char i;                               
    for(i=0; i<NO_OF_DIR_LEDS; i++)                   
            liftLEDExit(to_string(dir_leds[i]));   
    for(i=0; i<NO_OF_FLOORS; i++)                   
    {
        liftLEDExit(to_string(pos_leds[i]));       
        liftLEDExit(to_string(lift_leds[i]));       
        liftButtonExit(to_string(lift_buttons[i]));   
    }
    cout << "\n=== Demonstration END ===\n" << endl;
}
//===================================================================
void liftDefaultPos(void)
{
    liftLEDOn(to_string(pos_leds[DEFAULT_LIFT_POS]));   
}
//==================================================================
void liftDirUp(void)
{
    unsigned char i;                               
    /* Simulate lift going UP */
    for(i=0; i<NO_OF_DIR_LEDS; i++)                   
    {
            liftLEDOn(to_string(dir_leds[i]));       
            usleep(1000 * 500);                       
    }
    /* Turn all the direction LEDs OFF */
    for(i=0; i<NO_OF_DIR_LEDS; i++)                   
        liftLEDOff(to_string(dir_leds[i]));           
}
//==================================================================
void liftDirDown(void)
{
    char i;                                           
    /* Simulate lift going DOWN */
    for(i=NO_OF_DIR_LEDS; i>0; i--)                   
    {
        liftLEDOn(to_string(dir_leds[i-1]));       
        usleep(1000 * 500);                           
    }
    /* Turn all the direction LEDs OFF */
    for(i=0; i<NO_OF_DIR_LEDS; i++)                   
        liftLEDOff(to_string(dir_leds[i]));           
}
//==================================================================
int gpioFdOpen(unsigned int gpio)
{
    int fd;                                           
    string gp_num = to_string(gpio);               
    string path(SYSFS_GPIO_DIR);                   
                                                   
    const char *gp_file = (path + "/gpio" + gp_num + "/value").c_str();
    fd = open(gp_file, O_RDONLY);                   
    if (fd < 0)                                       
    {
        perror("gpioFdOpen");                       
    }
    return fd;                                       
}
//==================================================================
void liftButtonOpen(void)
{
    unsigned char i;                                   
    int button_fd;                                       
    for(i=0; i<NO_OF_FLOORS; i++)                       
    {
        button_fd = gpioFdOpen(floor_set[i].button);   
         if (button_fd < 0)                               
         {
                printf("Cannot open file handle for Lift button #%d\n", i);       
                exit(0);                                                       
          }
        floor_set[i].fd = button_fd;                   
    }
}
//=================================================================
void seekAllButtons(void)
{
    int i;                                           

    FD_ZERO(&read_fds);                               
    max_fd = 0;                                       
    for(i=0; i<NO_OF_FLOORS; i++)                   
    {
        FD_SET(floor_set[i].fd, &read_fds);           
        if(floor_set[i].fd > max_fd)               
        max_fd = floor_set[i].fd;               
        lseek(floor_set[i].fd, 0, SEEK_SET);       
        read(floor_set[i].fd, buf, MAX_BUF);       
    }
}
//================================================================
int liftGetInput(void)
{
    int ret=-1, fds;                               
    unsigned int i;                                   
    seekAllButtons();                               
    cout << "\nPress any LIFT button..." << endl;   
    ret = select(max_fd+1, NULL, NULL, &read_fds, NULL);
    if(ret < 0)                                       
    {
          perror("select failed");                   
          exit(0);                                   
    }
    for(i=0; i<NO_OF_FLOORS; i++)                   
    {
        fds = floor_set[i].fd;                       
        if(FD_ISSET(fds, &read_fds))               
        {                                           
            cout << "LIFT button is pressed for floor #" << i << endl;   
            liftLEDOn(to_string(floor_set[i].led));           
            sleep(1);                               
            ret = i;                               
            break;                                   
        }
    }
  return ret;                                       
}
//=================================================================
void sigfunc(int s)
{
    liftExitAll();               
    exit(0);                   
}
//=============================================================
int main(int argc, char* argv[])
{
    int cur_flr, new_flr, tmp;       
    cout << "Lift Operation Simulation using C++" << endl;
    cout << "-----------------------------------------------" << endl;
    signal(SIGINT, sigfunc);                                   
    liftInitAll();       
    liftButtonOpen();                                           
    liftDefaultPos();           
    cur_flr = DEFAULT_LIFT_POS;       
    while(1)                                                   
    {
        new_flr = liftGetInput();   
        if(new_flr < 0)                                       
            continue;
        /* Case 1: Lift is called on upper floor */
        if(new_flr > cur_flr)                                           
        {
            tmp = cur_flr;                                           
            cout << "LIFT going UP to floor #" << new_flr << endl;   
            while (tmp != new_flr)                                   
            {
                liftDirUp();                                           
                usleep(100);                                           
                liftLEDOff(to_string(pos_leds[tmp]));                   
                tmp++;                                               
                liftLEDOn(to_string(pos_leds[tmp]));                                                           
                usleep(1000 * 500);                                   
            }
        }
        /* Case 2: Lift is called to lower floor */
        else if (new_flr < cur_flr)                                   
        {
            tmp = cur_flr;                                           
            cout << "LIFT going DOWN to floor #" << new_flr << endl;   
            while (tmp != new_flr)                                   
            {
                liftDirDown();                                            usleep(100);                                            liftLEDOff(to_string(pos_leds[tmp]));                            tmp--;                                                liftLEDOn(to_string(pos_leds[tmp]));                            usleep(1000 * 500);                                       
            }
        }
        cur_flr = new_flr;                                        liftLEDOff(to_string(lift_leds[new_flr]));                   
        sleep(1);                                                       
    }
    return 0;
}














OUTPUT:

* ON HOST  MACHINES :


administrator@administrator-OptiPlex-390:~$ cd Desktop/ 

administrator@administrator-OptiPlex-390:~/Desktop$ pwd 
/home/administrator/Desktop 
administrator@administrator-OptiPlex-390:~/Desktop$ scp /home/administrator/Desktop/01elevator_cpp  root@192.168.7.2:/home/debian/Desktop/ 
Debian GNU/Linux 7 

BeagleBoard.org BeagleBone Debian Image 2014-04-23 

Support/FAQ: http://elinux.org/Beagleboard:BeagleBoneBlack_Debian 
01elevator_cpp                100%   72     0.1KB/s   00:00    
administrator@administrator-OptiPlex-390:~/Desktop$ 

//==================================================================//

* ON BeagleBoard :


administrator@administrator-OptiPlex-390:~$ ssh root@192.168.7.2 
Debian GNU/Linux 7 

BeagleBoard.org BeagleBone Debian Image 2014-04-23 

Support/FAQ: http://elinux.org/Beagleboard:BeagleBoneBlack_Debian 
Last login: Wed Apr 23 20:37:20 2014 from administrator-optiplex-397.local
root@beaglebone:/# cd /home/debian/Desktop/ 

root@beaglebone:/home/debian/Desktop# pwd 
/home/debian/Desktop

root@beaglebone:/usr/src#  g++ 01elevator_cpp.cpp -o 01_elevator 
root@beaglebone:/usr/src# ./01_elevator

Lift Operation Simulation using C++ 
----------------------------------------------- 

Press any LIFT button... 
LIFT button is pressed for floor #1 
LIFT going UP to floor #1 

Press any LIFT button... 
LIFT button is pressed for floor #3 
LIFT going UP to floor #3 

Press any LIFT button... 
LIFT button is pressed for floor #2 
LIFT going DOWN to floor #2 

Press any LIFT button... 
LIFT button is pressed for floor #0 
LIFT going DOWN to floor #0 

Press any LIFT button... 
LIFT button is pressed for floor #1 
LIFT going UP to floor #1 

Press any LIFT button... 
LIFT button is pressed for floor #0 
LIFT going DOWN to floor #0 

Press any LIFT button... 
LIFT button is pressed for floor #3 
LIFT going UP to floor #3 

Press any LIFT button... 












**************************************************

 Grp-A 2].

**************************************************


//==================================================================
// ASSIGNMENT NO :A (2)
// TITLE : Develop an application using Beeglebone Black/ ARM Cortex A5 development   
//                        board to simulate the working of signal lights. 
// ROLL NO :
// BATCH : T
//===================================================================

/* standard C++ header files */
#include<iostream>
#include<fstream>
#include<string>
#include<sstream>
#include<csignal>
#include <cstdlib>
//===================================================================
#define     LED_1        (0 * 32) + 3        /* GPIO0_3 */
#define     LED_2        (0 * 32) + 23        /* GPIO0_23 */
#define     LED_3        (0 * 32) + 2        /* GPIO0_2 */
#define     LED_4        (0 * 32) + 26        /* GPIO0_26 */

#define     LED_5        (1 * 32) + 17        /* GPIO1_17 */
#define     LED_6        (1 * 32) + 15        /* GPIO1_15 */
#define     LED_7        (0 * 32) + 15        /* GPIO0_15 */
#define     LED_8        (1 * 32) + 14        /* GPIO1_14 */

#define     LED_9        (0 * 32) + 14        /* GPIO0_14 */
#define     LED_10    (0 * 32) + 27        /* GPIO0_27 */
#define     LED_11    (0 * 32) + 22        /* GPIO0_22 */
#define     LED_12    (2 * 32) + 1        /* GPIO2_1 */
//===================================================================                                       
#define     NORTH_GREEN        LED_1       /* LD1 */
#define     NORTH_YELLOW        LED_5        /* LD5 */
#define     NORTH_RED            LED_9        /* LD9 */

#define     EAST_GREEN        LED_2        /* LD2 */
#define     EAST_YELLOW        LED_6        /* LD6 */
#define     EAST_RED            LED_10    /* LD10 */

#define     SOUTH_GREEN        LED_3        /* LD3 */
#define     SOUTH_YELLOW        LED_7        /* LD7 */
#define     SOUTH_RED            LED_11    /* LD11 */

#define     WEST_GREEN        LED_4        /* LD4 */
#define     WEST_YELLOW        LED_8        /* LD8 */
#define     WEST_RED            LED_12    /* LD12 */
//===================================================================
/* Use std namespace for various C++ definitions */
using namespace std;

/* PATH of a GPIO specific sysfs interfce directory on Linux system */
#define SYSFS_GPIO_DIR "/sys/class/gpio"
//===================================================================
void gpioExport(string gpio)
{
       fstream fs;                                           
       string path(SYSFS_GPIO_DIR);                           
       fs.open((path + "/export").c_str(), fstream::out);   
       fs << gpio;                                           
       fs.close();                                           
}
//===================================================================void gpioUnexport(string gpio)
{
       fstream fs;                                           
       string path(SYSFS_GPIO_DIR);                           
       fs.open((path + "/unexport").c_str(), fstream::out);   
       fs << gpio;                                               fs.close();                                           
}
//===================================================================
void gpioSetDir(string gpio, string dir)
{
       fstream fs;                                           
       string path(SYSFS_GPIO_DIR);                           

       fs.open((path + "/gpio" + gpio + "/direction").c_str(), fstream::out);
       fs << dir;                                               fs.close();                                           
}
//==================================================================
void gpioSetValue(string gpio, string val)
{
       fstream fs;                                              
     string path(SYSFS_GPIO_DIR);                           
          fs.open((path + "/gpio" + gpio + "/value").c_str(), fstream::out);
       fs << val;                                               fs.close();                                           
}
//===================================================================
string to_string(int a)
{
    ostringstream temp;                   
    temp<<a;                           
    return temp.str();                   
}
//===================================================================
void lightExit(string light)
{
    gpioSetValue(light, "0");           
    gpioUnexport(light);               
}
//===================================================================
void lightInit(string light)
{
    gpioExport(light);                   
    gpioSetDir(light, "out");           
    gpioSetValue(light, "0");           
}
//===================================================================
void lightOn(string light)
{
    gpioSetValue(light, "1");           
}
//===================================================================
void lightOff(string light)
{
    gpioSetValue(light, "0");           
}
//===================================================================void trafficInitAll(void)
{
        lightInit(to_string(NORTH_GREEN));
        lightInit(to_string(NORTH_YELLOW));
        lightInit(to_string(NORTH_RED));

        lightInit(to_string(EAST_GREEN));
        lightInit(to_string(EAST_YELLOW));
        lightInit(to_string(EAST_RED));

        lightInit(to_string(SOUTH_GREEN));
        lightInit(to_string(SOUTH_YELLOW));
        lightInit(to_string(SOUTH_RED));

        lightInit(to_string(WEST_GREEN));
        lightInit(to_string(WEST_YELLOW));
        lightInit(to_string(WEST_RED));
}
//==================================================================
void trafficExitAll(void)
{
        lightExit(to_string(NORTH_GREEN));
        lightExit(to_string(NORTH_YELLOW));
        lightExit(to_string(NORTH_RED));

        lightExit(to_string(EAST_GREEN));
        lightExit(to_string(EAST_YELLOW));
        lightExit(to_string(EAST_RED));

        lightExit(to_string(SOUTH_GREEN));
        lightExit(to_string(SOUTH_YELLOW));
        lightExit(to_string(SOUTH_RED));

        lightExit(to_string(WEST_GREEN));
        lightExit(to_string(WEST_YELLOW));
        lightExit(to_string(WEST_RED));
}
//===================================================================
void northSouthOn(void)
{
    lightOff(to_string(EAST_YELLOW));       
    lightOff(to_string(WEST_YELLOW));       
    lightOff(to_string(NORTH_RED));           
    lightOff(to_string(SOUTH_RED));           

    /* East-West traffic should STOP */
    lightOn(to_string(EAST_RED));           
    lightOn(to_string(WEST_RED));           

    /* North-South traffic should GO */
    lightOn(to_string(NORTH_GREEN));       
    lightOn(to_string(SOUTH_GREEN));       

    /* Pause in this state for 10 seconds using sleep() */
    sleep(10);

    lightOff(to_string(NORTH_GREEN));       
    lightOff(to_string(SOUTH_GREEN));       

    /* North-South traffic should WAIT */
    lightOn(to_string(NORTH_YELLOW));       
    lightOn(to_string(SOUTH_YELLOW));       

    /* Wait for 1 second */
    sleep(1);
}
//===================================================================void eastWestOn(void)
{
    lightOff(to_string(NORTH_YELLOW));       
    lightOff(to_string(SOUTH_YELLOW));       
    lightOff(to_string(EAST_RED));           
    lightOff(to_string(WEST_RED));           

    /* North-South traffic should STOP */
    lightOn(to_string(NORTH_RED));           
    lightOn(to_string(SOUTH_RED));           

    /* East-West traffic should GO */
    lightOn(to_string(EAST_GREEN));           
    lightOn(to_string(WEST_GREEN));           

    /* Pause in this state for 10 seconds using sleep() */
    sleep(10);

    lightOff(to_string(EAST_GREEN));       
    lightOff(to_string(WEST_GREEN));       

    /* East-West traffic should WAIT */
    lightOn(to_string(EAST_YELLOW));       
    lightOn(to_string(WEST_YELLOW));       

    /* Wait for 1 second */
    sleep(1);
}
//===================================================================void sigfunc(int s)
{
    trafficExitAll();           
    std::exit(0);               
}
//===================================================================
int main(int argc, char* argv[])
{
    cout << "\nTraffic Signal Light Simulation using C++" << endl;
    cout << "-----------------------------------------------" << endl;

    signal(SIGINT, sigfunc);               
    trafficInitAll();                       
    sleep(2);                               
    for(int i=0; i<10; i++)                   
    {
        /* Some prints to indicate traffic direction */
        cout << "\nNORTH-SOUTH    --> [GO]" << endl;
        cout << "EAST-WEST         --> [STOP]\n" << endl;
        northSouthOn();                       
        sleep(1);                           

        /* Some prints to indicate traffic direction */
        cout << "\nEAST-WEST     --> [GO]" << endl;
        cout << "NORTH-SOUTH     --> [STOP]\n" << endl;
        eastWestOn();                       
        sleep(1);                           
    }
    trafficExitAll();                       
    cout << "Done." << endl;               
}


OUTPUT:

* ON HOST  MACHINES :


administrator@administrator-OptiPlex-390:~$ cd Desktop/ 

administrator@administrator-OptiPlex-390:~/Desktop$ pwd 
/home/administrator/Desktop 
administrator@administrator-OptiPlex-390:~/Desktop$ scp /home/administrator/Desktop/01elevator_cpp  root@192.168.7.2:/home/debian/Desktop/ 
Debian GNU/Linux 7 

BeagleBoard.org BeagleBone Debian Image 2014-04-23 

Support/FAQ: http://elinux.org/Beagleboard:BeagleBoneBlack_Debian 
02traffic_cpp                100%   72     0.1KB/s   00:00    
administrator@administrator-OptiPlex-390:~/Desktop$ 

//==================================================================//

* ON BeagleBoard :


administrator@administrator-OptiPlex-390:~$ ssh root@192.168.7.2 
Debian GNU/Linux 7 

BeagleBoard.org BeagleBone Debian Image 2014-04-23 

Support/FAQ: http://elinux.org/Beagleboard:BeagleBoneBlack_Debian 
Last login: Wed Apr 23 20:37:20 2014 from administrator-optiplex-397.local
root@beaglebone:/# cd /home/debian/Desktop/ 

root@beaglebone:/home/debian/Desktop# pwd 
/home/debian/Desktop

root@beaglebone:/usr/src#  g++ 01traffic_cpp.cpp -o 01_traffic
root@beaglebone:/usr/src# ./01_traffic


Traffic Signal Light Simulation using Python 
----------------------------------------------- 

NORTH-SOUTH    --> [GO] 
EAST-WEST     --> [STOP] 


EAST-WEST    --> [GO] 
NORTH-SOUTH     --> [STOP] 


NORTH-SOUTH    --> [GO] 
EAST-WEST     --> [STOP] 


EAST-WEST    --> [GO] 
NORTH-SOUTH     --> [STOP] 


NORTH-SOUTH    --> [GO] 
EAST-WEST     --> [STOP] 


EAST-WEST    --> [GO] 
NORTH-SOUTH     --> [STOP] 


NORTH-SOUTH    --> [GO] 
EAST-WEST     --> [STOP] 


EAST-WEST    --> [GO] 
NORTH-SOUTH     --> [STOP] 


NORTH-SOUTH    --> [GO] 
EAST-WEST     --> [STOP] 


EAST-WEST    --> [GO] 
NORTH-SOUTH     --> [STOP] 


NORTH-SOUTH    --> [GO] 
EAST-WEST     --> [STOP] 


EAST-WEST    --> [GO] 
NORTH-SOUTH     --> [STOP] 


NORTH-SOUTH    --> [GO] 
EAST-WEST     --> [STOP] 


EAST-WEST    --> [GO] 
NORTH-SOUTH     --> [STOP] 


NORTH-SOUTH    --> [GO] 
EAST-WEST     --> [STOP] 

done







**************************************************

 Grp-A 3].

**************************************************



(defvar a)
(defvar b)
(defvar c)
(defvar d)     


(write-line " Enter two numbers in decimal : ")

  
    (setf a(read))
    (setf b(read))

    (sb-thread:make-thread(lambda()
                (progn
                (sleep 0)
                (setf c(+ a b))
                (print "ADDITION in binary: ")
                (format t " ~b" c )
                (print "ADDITION in decimal: ")
                (print c))))

    (sb-thread:make-thread(lambda()(progn(sleep 0)
                (setf c(- a b))
                (print "SUBTRACTION in binary: ")
                (format t " ~b" c )
                (print "SUBTRACTION in decimal: ")
                (print c))))

     (sb-thread:make-thread(lambda()(progn(sleep 0)
                (setf c(* a b))
                (print "MULTIPLICATION in binary: ")
                (format t " ~b" c )
                (print "MULTIPLICATION IN DECIMAL: ")
                (print c))))

    (sb-thread:make-thread(lambda()(progn(sleep 0)
                (setf c(* a a))
                (print "SQUARE in binary: ")
                (format t " ~b" c )
                (print "SQUARE OF 1st NUMBER  : ")
                (print c))))

    (sb-thread:make-thread(lambda()(progn(sleep 0)
                (setf c(* b b b))
                (print "CUBE OF 2ND NUMBER : ")
                (print c))))  


    (sb-thread:make-thread(lambda()(progn(sleep 0)
                (setf c(sin a))
                (print "SINE OF 1ST NUMBER : ")
                (print c))))

    (sb-thread:make-thread(lambda()(progn(sleep 0)
                (setf c(tan a))
                (print "TAN OF 1ST NUMBER : ")
                (print c))))

    (sb-thread:make-thread(lambda()(progn(sleep 0)
                (setf c(cos a))
                (print "COSINE OF 1ST NUMBER : ")
                (print c))))

    (sb-thread:make-thread(lambda()(progn(sleep 0)
                (setf c(acos a))
                (print "SEC OF 1ST NUMBER : ")
                (print c))))

    (sb-thread:make-thread(lambda()(progn(sleep 0)
                (setf c(asin a))
                (print "COSEC OF 1ST NUMBER : ")
                (print c))))

    (sb-thread:make-thread(lambda()(progn(sleep 0)
                (setf c(atan a))
                (print "COT OF 1ST NUMBER : ")
                (print c))))



    (sb-thread:make-thread(lambda()(progn(sleep 0)
                (setf c(min a b))
                (print "MINIMUM NUMBER : ")
                (print c))))

    (sb-thread:make-thread(lambda()(progn(sleep 0)
                (setf c(max a b))
                (print "MAXIMUM NUMBER : ")
                (print c))))

     

(exit)



*************output*********************

gescoe@gescoe-OptiPlex-3010:~/Desktop/new$ sbcl
This is SBCL 1.1.14.debian, an implementation of ANSI Common Lisp.
More information about SBCL is available at <http://www.sbcl.org/>.

SBCL is free software, provided as is, with absolutely no warranty.
It is mostly in the public domain; some portions are provided under
BSD-style licenses.  See the CREDITS and COPYING files in the
distribution for more information.
* (load "calculator.lisp")
 Enter two numbers in decimal :
90
0

"ADDITION in binary: "  1011010
"ADDITION in decimal: "
90
"SUBTRACTION in binary: "  1011010
"SUBTRACTION in decimal: "
90
"MULTIPLICATION in binary: "  0
"MULTIPLICATION IN DECIMAL: "
0
"SQUARE in binary: "  1111110100100
"SQUARE OF 1st NUMBER  : "
8100
"CUBE OF 2ND NUMBER : "
0
"SINE OF 1ST NUMBER : "
0.89399666
"TAN OF 1ST NUMBER : "
-1.9952004
"COSINE OF 1ST NUMBER : "
-0.44807363
"SEC OF 1ST NUMBER : "
#C(0.0 5.192926)
"COSEC OF 1ST NUMBER : "
#C(1.5707964 -5.192926)
"COT OF 1ST NUMBER : "
1.5596857
"MINIMUM NUMBER : "
0
"MAXIMUM NUMBER : "
90



**************************************************

 Grp-A 5].

**************************************************





ASSIGNMENT NO.:-

Aim: - Assignment to Create Project plan, SRS, Design document and Test Plan for one group-C assignment(Stepper Motor) from embedded operating system or Concurrent and Distributed Programming.

Objective: To create the project plan, SRS, design document and test plan.
PROJECT PLAN:-
Project planning is a discipline for stating how to complete a project within a certain timeframe, usually with defined stages, and with designated resources. A project plan, according to the Project Management Body of Knowledge, is: "...a formal, approved document used to guide both project execution and project control. The primary uses of the project plan are to document planning assumptions and decisions, facilitate communication among stakeholders, and document approved scope, cost, and schedule baselines. A project plan may be summarized or detailed. The objective of a project plan is to define the approach to be used by the Project team to deliver the intended project management scope of the project.
At a minimum, a project plan answers basic questions about the project:
  • Why? - What is the problem or value proposition addressed by the project? Why is it being sponsored?
  • What? - What is the work that will be performed on the project? What are the major products/deliverables?
  • Who? - Who will be involved and what will be their responsibilities within the project? How will they be organized?
  • When? - What is the project timeline and when will particularly meaningful points, referred to as milestones, be complete?
Project plan for Stepper Motor is as follows:
Table:
Category
Recommended Action Item
Time span

  1. Planning and gathering requirement
  • Make algorithm for project
  • Requirement include Beagle Bone and System with required software

2. System
  • Start to create the project.
  • Generate the code.
4 hrs
3. Beagle Bone Black
  • Create a connection between system & beagle board.
  • Check whether the beagle board successfully installed or not?


2 hrs
4. Stepper Motor
  • Create a connection between beagle board and stepper motor.


15 min.
5. Testing of Project
  • Testing of connection with Beagle bone and Stepper motor
  • Testing Results
20 Min
SRS(Software Requirements Specifications):-

Software Requirements Specification (SRS) is a perfect detailed description of the behavior of the system to be developed. That is SRS document is an agreement between the developer and the customer covering the functional and non functional requirements of the software to be developed. SRS is considered as a contract between the customer and the developer. This SRS document will be  used for verifying whether all the functional and non functional requirements specified in the SRS are implemented in the product.  The complete description of the functions to be performed by the software specified in the SRS will assist the potential users to determine if the software specified meets their needs or how the software must be modified to meet their needs. 
  1. Flexibility:
Flexibility is the first software requirement specification for any project. The flexibility of the stepper motor depends on frequency of the stepper motor. If the frequency is increased rotation of the stepper motor is increased. And the frequency is decreased then the rotation of the stepper motor is also decreased.

  1. Performance:
Performance of the system is depends on the working of all the hardware and software components of the system which are used in project developments. As well as performance of the system also depends on code, which is used for developing the project. The code should be more flexible, scalable, and easy to implement.

  1. Design constraints imposed on an implementation:
  1. Hardware Requirements:
1. PC(x86 Architecture)
2. Beagle Bone Black
3. Stepper Motor Board
4. Power supply cable 5v and 12v
b) Software Requirements:
  1. Beagle Bone Drives
  2. Power Supply
  3. Operating System
  4. gcc compiler on target for direct compilation of source.

General Technical Specifications:
1) Hardware:
Supply, installation, commissioning and maintenance of all necessary hardware and networking equipments and its connectivity as specified in the detailed specification. As a part of the project, the vendor should procure the required hardware and build the infrastructure as detailed in the Specifications. The vendor shall take the responsibility to install the servers, switches, routers, backup and tape devices, Workstation PCs, and other necessary hardware/software at the sites defined in the bid proposal sheet.


2) Networking:
The scope of work covers supply, installation, commissioning and maintenance of LAN at datacenter, Customer care centers, Sub division, division, Circle, Head Quarter and any other office of the utility as per their requirement along with creation of VPN/ MPLS based WAN solution. The vendor shall also provide the necessary drawings and plan for installation, sizing, cabling and connectivity and the bill of material for the networking
of all the locations specified herein.

3) GIS System Software and maps:
Supply, installation, commissioning and maintenance of GIS software and latest satellites imagery maps for GIS based customer indexing and asset mapping in the specified town. The successful bidder shall provide the maps along with the certificate and rights in favor of owner from the source that these are the latest as on date of purchase which should be later to award date.

DESIGN DOCUMENTS:-

The following documents (one set each) will be required for smooth functioning of the system at
data center and DR center:
The successful vendor will provide ongoing product information for referential purposes and facilitating self-education by Utility personnel.
Key aspects that the vendor will be evaluated on but not limited to include:
What documentation is included in the standard license fee, for example:
  • User manuals;
  • Technical manuals;
  • Installation guides;
  • Business process guides;
  • Program flow descriptions;
  • Data model descriptions;
  • Sample reports;
  • Screen formats;
  • Toolkit guides;
  • Troubleshooting guides;
  • Frequently asked question (FAQ) guides.

Introduction of Stepper Motor Basics:
Working of stopper motor:
  • Stepper motor consists of main parts called rotor and stator. A rotor is permanent magnetic rotating shaft in the middle and stator is the electromagnets positioned at specified location surrounding the rotor.


  • Fig. Shows the arrangement of stator and rotor:


  • The middle motor align itself with the magnetic field created as the effect of polarization
of each stator. Once a stator is electrocuted i.e. provided with a high voltage, it is magnetized and creates north and south poles of its own. As a result of this the middle rotor i.e. permanent magnet gets attracted towards the magnetized stator.
  • The motor rotates 900 , in each step. Such scenario is known as full step mode of operation.
Table: Working off step motor
D
C
B
A
0
0
0
1
0
0
1
0
0
1
0
0
1
0
0
0
1:Stator is magnetized
0: Stator in the normal state
Interfacing with Beagle Bone:-
We are using pin configuration to interface beagle board with stepper motor:
BBB P9 slot has been used for interfacing with stepper motor.
Stepper motor is connected on a PCB board with 4 stators connected to FRC26 connector pins in the format ‘A’ stator from stepper motor to pin no. 19 on FRC, similarly ‘B’ on 20,’C’ on 21,’D’ on 22.
Pins 11,12,13,14 from BBB P9 are connected to FRC pins on PCB board.
This configuration is shown in table
Connector slot no.
BBB PIN no.
PIN Description
PIN connects to stepper motor connected FRC
Function
P9
1,2
GND
GND
GND
P9
5
VCC[5V]
VCC
VCC
P9
11
GPIO[30]
FRC-21 pin
OUT
P9
12
GPIO[28]
FRC-22 pin
OUT
P9
13
GPIO[31]
FRC-19 pin
OUT
P9
14
GPIO[18]
FRC-20 pin
OUT

Each BBB pin GPIO number associated with it referred as GPIOX_Y.
Once BBB pins are selected for connection, calculate the GPIO pin number using BBB architecture and formula ((X*32)+Y).
This GPIO number will be used in program using value parameter. All the stators will be activated by setting its pin value to high i.e. 1.
Once the connection is done we are ready to write our program and performing GPIO setting (activation and direction) on Beagle Bone.

TEST PLAN:-

Test plans are prepared for each phase of testing. The initial test plan is created during the Project Planning phase. The initial test plan describes who performs which type of testing and when. Ideally master test plan covers all types of test i.e. from unit testing to production testing. The Lead Partner along with consortium partners is expected to submit the test plans to Utility for approval. Any changes made to the test plan during the project life cycle should be communicated to UTILITY for approval.


Test plans contains following items:
_ Roles and responsibilities of test team
o Approach to testing
o Function testing
o Security testing
o User Interface and reports testing
o Concurrency testing
o Performance and Load testing
_ Test Scenarios along with entry and exit criteria
_ Test specifications
_ Suspension and resumption criteria


Sr No.
Test Case Name
Steps/Action
Expected Result
Actual Result
Remark
1
Checking connections between system and Beagle bone
Whether GPIO is assign or not
Beagle bone should be connected successfully.
Beagle bone was connected successfully.
Pass
2
Checking connection between Beagle bone and Stepper motor
Whether stepper motor working according to beagle bone or not
Stepper motor should be connected successfully
Stepper motor was connected successfully
Pass
3
Checking code
Whether code working right or not
Code should be correct
Code was correct
Pass
4
Checking Result
Whether result is generated or not
Result should be correct
Result was correct
Pass



Testing and Assurance:-

Testing and quality assurance in software development is more rigorous since each component has to be more reliable, if it is to be reused. A system is tested at various stages of development and deployment. For example, each component is tested as a unit for checking the correctness of its own code. Further, the component is tested with its dependent components. After final release of the entire set of components, system is tested for the correctness of system functionality. Finally the components are further tested in simulated production load for performance and load analysis. The Lead Partner along with consortium partners shall be responsible for the testing processes such as planning (includes preparing test plans and defining roles and their responsibilities), preparation (consists of preparing test specification, test environment and test data) and execution (includes testing at various levels like unit level, integration level, system level and production).


CONCLUSION: - Hence, we have successfully developed the Project plan, SRS, Design document and Test Plan for one group-C assignment from embedded operating system or Concurrent and Distributed Programming.





**************************************************

 Grp-A 6].

**************************************************




/*================================================================
Assignment No. A-6
Title : Write an application to parse input text file concurrently and       compare the result of concurrent parsing with serial parsing (       Use concurrent YACC parser)
Batch :
Roll no : 
=============================================================*/





----------program----------

-----lex_pgm.j ------

%{
#include&lt;stdio.h&gt;
%}
letter [a-zA-Z]
digit [0-9]
under [_]
%%
void |
int |
char |
include |
main |
printf |
if |
for |
break |
while {printf("\n %s is a keyword\n",yytext);}
"+" |
"-" |
"*" |
"/" {printf("\n %s is a binary operator",yytext);}
{digit}+ {printf("\n%s is an integer constant\n",yytext);}
{letter}({letter}|{digit}|{under})* {printf("\n %s is an identifier\n",yytext);}
\"[a-zA-Z0-9\(\)\% ]*\" {printf("\n%s is a literal\n",yytext);}

%%
int main(int argc, char **argv)
{
FILE *fp;
fp=fopen(argv[1],"r");//argv[1] is string array has data taken //from file 
yyin=fp;
yylex();
return 1;
}

yywrap()
{}




-------openmp.c -----------

#include&lt;stdio.h&gt;
#include&lt;omp.h&gt;
#include&lt;string.h&gt;
int main(int argc, char **argv)
{
#pragma omp parallel
{
int tid=omp_get_thread_num();
char inst[100];
strcpy(inst,"./yacc_file ");
strcat(inst,argv[tid+1]);
system(inst);
}
}


------------------ INPUT FILES -----------------


------------- Pl1.txt ----------

main()
{
printf("jshdjfash dsfasdf sa");
}


------------- Pl2.txt ----------

main()
{
int x, y;
}


-------------pl3.txt----------

int abc;
char yx;
fun();


-------------pl4.txt----------

main()
{
while()
switch()
}





----------OUTPUT----------

op:yacc

[estudymoney@localhost ~]# lex lex_pgm.l
[estudymoney@localhost ~]# cc lex.yy.c -o yacc_file
[estudymoney@localhost ~]# gcc openmp.c -fopenmp
[estudymoney@localhost ~]# ./a.out p1.c p2.c p3.c p4.c

 main is a keyword
()
{

 while is a keyword
()

 switch is an identifier
()
}


 main is a keyword
()
 main is a keyword
()
{
{

 int is a keyword
 
 x is an identifier

 printf is a keyword
(
"jshdjfash dsfasdf sa" is a literal
);
}
 y is an identifier
;
}

 int is a keyword
 
 abc is an identifier
;

 char is a keyword
 
 yx is an identifier
;

 fun is an identifier
();
[estudymoney@localhost ~]#





**************************************************

 Grp-B 1].

**************************************************





#================================================================
#
#
#================================================================
#!/usr/bin/python
#================================================================
import sys
import time
#================================================================
SYSFS_GPIO_DIR = "/sys/class/gpio"
#================================================================
def gpioUnexport (gpio):
    try:
           fo = open(SYSFS_GPIO_DIR + "/unexport","w") 
           fo.write(gpio)
           fo.close()
           return
       except IOError:
         return
#================================================================
def gpioExport (gpio):
    try:
           fo = open(SYSFS_GPIO_DIR + "/export","w") 
           fo.write(gpio)
           fo.close()
           return
       except IOError:
                return
#================================================================
def gpioSetDir (gpio, flag):
    try:
           fo = open(SYSFS_GPIO_DIR + "/gpio" + gpio + "/direction" ,"w") 
           fo.write(flag)
           fo.close()
           return
     except IOError:
                return
#================================================================
def gpioSetVal (gpio, val):
    try:
        fo = open(SYSFS_GPIO_DIR + "/gpio" + gpio + "/value" ,"w") 
        fo.write(val)
        fo.close()
        return
    except IOError:
                return
#================================================================
def lightExit (gpio):
    gpioSetVal(gpio, val="0")
    gpioUnexport(gpio)
    return
#================================================================   
def lightInit (gpio):
    gpioExport(gpio)
    gpioSetDir(gpio, flag="out")
     gpioSetVal(gpio, val="0")
     return
#================================================================    
def lightOn (gpio):
    gpioSetVal(gpio, val="1")
    return
#================================================================   
def lightOff (gpio):
    gpioSetVal(gpio, val="0")
    return
#================================================================   
try:   
    lightInit(str(23))   
    for i in range(0,3):
        lightOn(str(23))
        time.sleep(1)
        lightOff(str(23))
        time.sleep(1)

    lightExit(str(23))
except KeyboardInterrupt:
    exit()
        sys.exit(0)





**************************************************

 Grp-B 4].

**************************************************




/*---------------------------------------------------------------------------------------------------------
Assignment No :B(4)
Title     : Implement a Parallel ODD-Even Sort algorithm using GPU or ARM equivalent.
Roll No     :
Batch     : 
-----------------------------------------------------------------------------------------------------------*/
//===================================================================
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <omp.h>

#define NO_OF_THREADS    2
#define ARR_SIZE    20
#define DIVIDER        10000

int num_arr[ARR_SIZE];
//===================================================================
void print_sorted_arr(int *a)
{
    int i;
    printf("\nSorted Array is: [");
    for(i=0; i<ARR_SIZE; i++)
    {
        if(i+1 == ARR_SIZE)
            break;
        printf("%d, ", a[i]);
    }
    printf("%d]\n", a[i]);

//================================================================
void get_random_arr()
{
    int i;
    printf("\nElements to Sort are: [");
    for(i=0; i<ARR_SIZE; i++)
    {
        num_arr[i] = rand()%DIVIDER;
        if(i+1 == ARR_SIZE)
            break;
        printf("%d, ", num_arr[i]);
    }
    printf("%d]\n", num_arr[i]);

}
//==============================================================
void odd_even_sort_openmp(int* a, int n)
{
  int phase, i, temp;
  for(phase=0;phase<n;++phase)
  {
    if(phase%2==0) //even phase
    {
        #pragma omp parallel for num_threads(NO_OF_THREADS) default(none) shared(a,n) private(i,temp)
        for(i=1;i<n;i+=2)
            if(a[i-1] > a[i])
            {
                temp = a[i];
                a[i] = a[i-1];
                a[i-1] = temp;
            }
    }
    else //odd phase
    {
        #pragma omp parallel for num_threads(NO_OF_THREADS) default(none) shared(a,n) private(i,temp)
        for(i=1;i<n-1;i+=2)
            if(a[i] > a[i+1])
            {
                temp = a[i];
                  a[i] = a[i+1];
                  a[i+1] = temp;
            }
    }
  }
}
//===================================================================
int main (void)
{
    int i;
    int* arr1;
    double start_time_omp, end_time_omp, elapsed_time_omp;

    printf("\nParallel Odd-Even Sort using OpenMP:");
    printf("\n------------------------------------------\n");

    /* Prepare data to sort */
    printf("\nData Array:");
    printf("\n-------------");
    get_random_arr();

    /* Allocate memory for new array */
    arr1 = (int*) malloc(sizeof(int)*ARR_SIZE);

    /* Copy data to sort in the new array */
    memcpy(arr1, num_arr, sizeof(int)*ARR_SIZE);

    /* Call function to sort the array. Also record the start and end time */
    printf("\nOpenMP Method:");
    printf("\n-----------------");
    printf("\nSorting the data parallely with OpenMP ...");
    start_time_omp = omp_get_wtime();
    odd_even_sort_openmp(arr1, ARR_SIZE);
    end_time_omp = omp_get_wtime();
    elapsed_time_omp = end_time_omp - start_time_omp;
    printf("[Done]\n");

    /* Print the result which is a sorted array */
    printf("\nResult of OpenMP:");
    printf("\n-----------------");
    print_sorted_arr(arr1);

    /* Print the result (Sorted Array) */
    printf("\nTime Info:");
    printf("\n-----------------");
    printf("\nTime taken to Run Algorithm\t: %lf (s)\n",elapsed_time_omp);

    /* Free the memory allocated by maclloc() */
    free(arr1);

    return 0;
}


*********
output
*********
administrator@administrator-OptiPlex-390:~$ ssh root@192.168.7.2
Debian GNU/Linux 7

BeagleBoard.org BeagleBone Debian Image 2014-04-23

Support/FAQ: http://elinux.org/Beagleboard:BeagleBoneBlack_Debian
Last login: Wed Apr 23 20:25:22 2014 from administrator-optiplex-405.local
root@beaglebone:~# cd /
root@beaglebone:/# cd home/debian/Desktop
root@beaglebone:/home/debian/Desktop# ls
a.out          gpio.cpp    hellobb    liftpins.py     new          te54
elevator      gpio.h    hellobb.c  liftpins.pyc  stepper.py
elevator.cpp  gpio.py    hellobbb   main         stepperpins.py
elevator.h    gpio.pyc    imp       main.c     stepperpins.pyc
elevator.py   hello    imp.cpp    main.cpp     te31
root@beaglebone:/home/debian/Desktop#  gcc -o main -fopenmp main.c
main.c: In function 'main':
main.c:100:2: warning: incompatible implicit declaration of built-in function 'memcpy' [enabled by default]
root@beaglebone:/home/debian/Desktop# ./main

Parallel Odd-Even Sort using OpenMP:
------------------------------------------

Data Array:
-------------
Elements to Sort are: [9383, 886, 2777, 6915, 7793, 8335, 5386, 492, 6649, 1421, 2362, 27, 8690, 59, 7763, 3926, 540, 3426, 9172, 5736]

OpenMP Method:
-----------------
Sorting the data parallely with OpenMP ...[Done]

Result of OpenMP:
-----------------
Sorted Array is: [27, 59, 492, 540, 886, 1421, 2362, 2777, 3426, 3926, 5386, 5736, 6649, 6915, 7763, 7793, 8335, 8690, 9172, 9383]

Time Info:
-----------------
Time taken to Run Algorithm    : 0.003384 (s)








**************************************************

 Grp-B 5].

**************************************************




#include<stdio.h>
#include<omp.h>
#define MAXTHREADS 5
#define ARRAYSIZE 20

int main()
{
    int a[]={1,2,3,5,6,3,8,7,3,11,3,85,852,41,2,3,8,6,9,7},i,j,found=0,key=3;

    double start_time,run_time;
    for(j=1;j<=5;j++)
    {
        omp_set_num_threads(j);
        found=0;
        start_time=omp_get_wtime();

        #pragma omp parallel private(i)
        {
            int start,noofsteps;

            #pragma omp single
            printf("num of threads in action: %d\n",j);
            if(found==0)
            {
                         start=(omp_get_thread_num())*(ARRAYSIZE/omp_get_num_threads());
                         noofsteps=start+(ARRAYSIZE/omp_get_num_threads());
            if(ARRAYSIZE%j!=0)
                noofsteps+=(ARRAYSIZE%j);
            for(i=start;i<noofsteps;i++)
                        if(key==a[i])
            {
                 printf("Key has found in %d thread at %d position \n",omp_get_thread_num(),i+1);
                found=1;
                break;   
                        }   
            }

        }
             run_time=omp_get_wtime()-start_time;
             printf("\n%fseconds %d threads\n",run_time,j);

            }
return 0;
}

/*\\output
administrator@administrator-OptiPlex-3010:~$ cd Desktop/
administrator@administrator-OptiPlex-3010:~/Desktop$ g++ nary.cpp -o nary -fopenmp
administrator@administrator-OptiPlex-3010:~/Desktop$ ./nary
num of threads in action: 1
Key has found in 0 thread at 5 position

0.000071seconds 1 threads
num of threads in action: 2
Key has found in 0 thread at 5 position
Key has found in 1 thread at 15 position

0.000108seconds 2 threads
num of threads in action: 3
Key has found in 1 thread at 8 position
Key has found in 2 thread at 15 position
Key has found in 0 thread at 5 position

0.000107seconds 3 threads
num of threads in action: 4
Key has found in 1 thread at 8 position
Key has found in 2 thread at 15 position
Key has found in 0 thread at 5 position

0.000075seconds 4 threads
num of threads in action: 5
Key has found in 3 thread at 15 position

0.001428seconds 5 threads
administrator@administrator-OptiPlex-3010:~/Desktop$ */



**************************************************

 Grp-B 7].

**************************************************


#include<cuda.h>
#include<cuda_runtime.h>
#include <iostream>

using namespace std;

#define BLOCK_SIZE 2

__global__ void gpuMM(float *A, float *B, float *C, int N)
{
    // Matrix multiplication for NxN matrices C=A*B
    // Each thread computes a single element of C
    int row = blockIdx.y*blockDim.y + threadIdx.y;
    int col = blockIdx.x*blockDim.x + threadIdx.x;

    float sum = 0.f;
    for (int n = 0; n < N; ++n)
        sum += A[row*N+n]*B[n*N+col];

    C[row*N+col] = sum;
}

int main(int argc, char *argv[])
{
    // Perform matrix multiplication C = A*B
    // where A, B and C are NxN matrices
    // Restricted to matrices where N = K*BLOCK_SIZE;
    int N,K;
    K = 2;
    N = K*BLOCK_SIZE;

    cout << "Executing Matrix Multiplcation" << endl;
    cout << "Matrix size: " << N << "x" << N << endl;

    // Allocate memory on the host
    float *hA,*hB,*hC;
    hA = new float[N*N];
    hB = new float[N*N];
    hC = new float[N*N];

    // Initialize matrices on the host
    cout<<"\n\t Enter matrix a : \n";
    for (int j=0; j<N; j++){
        for (int i=0; i<N; i++){
            //hA[j*N+i] = 2.f*(j+i);
            //hB[j*N+i] = 1.f*(j-i);

            cin>>hA[j*N+i];


        }

    }

    cout<<"\n\t Enter matrix B: \n";
    for (int j=0; j<N; j++){
            for (int i=0; i<N; i++){
                //hA[j*N+i] = 2.f*(j+i);
                //hB[j*N+i] = 1.f*(j-i);


                cin>>hB[j*N+i];

            }

        }

    // Allocate memory on the device
    int size = N*N*sizeof(float);    // Size of the memory in bytes
    float *dA,*dB,*dC;
    cudaMalloc(&dA,size);
    cudaMalloc(&dB,size);
    cudaMalloc(&dC,size);

    dim3 threadBlock(BLOCK_SIZE,BLOCK_SIZE);
    dim3 grid(K,K);

    // Copy matrices from the host to device
    cudaMemcpy(dA,hA,size,cudaMemcpyHostToDevice);
    cudaMemcpy(dB,hB,size,cudaMemcpyHostToDevice);

    //Execute the matrix multiplication kernel

    gpuMM<<<grid,threadBlock>>>(dA,dB,dC,N);

    // Now do the matrix multiplication on the CPU
    float c;
    for (int i=0; i<N; i++){
        for (int j=0; j<N; j++){
            c = 0.f;
            for (int k=0; k<N; k++){
                c=c+ hA[i*N+k]*hB[N*j+k];
            }
            hC[i*N+j] = c;
        }
    }

    // Allocate memory to store the GPU answer on the host
    float *C;
    C = new float[N*N];

    // Now copy the GPU result back to CPU
    cudaMemcpy(C,dC,size,cudaMemcpyDeviceToHost);
    cout<<"\nAnswer matrix...\n";
        for (int j=0; j<N; j++){
                for (int i=0; i<N; i++){
                    cout<<"\n"<<C[j*N+i];
                }
            }
    int flag=0;
    // Check the result and make sure it is correct
    for (int row=0; row<N; row++){
        for (int col=0; col<N; col++){
            if ( C[row*N+col] != hC[row*N+col] ){
                flag=0;
                cout<<"\n\n\t Wrong answer.........";
                row = col = N;
            }
            else
            {
                flag=1;
            }

        }
    }
    if(flag==1)
    {
        cout<<"\n\n\t Correct answer.......";
    }
    else
    {
        cout<<"\n\n\t Wrong answer.........";
    }




    cout << "Finished." << endl;

}


/*output

Executing Matrix Multiplcation
Matrix size: 4x4

     Enter matrix a :
1
1
1
1
1
1
1
1
1
1
1
1

1
1
1
1

     Enter matrix B:
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1

Answer matrix...

4
4
4
4
4
4
4
4
4
4
4
4
4
4
4
4

     Correct answer.......Finished.
*/







**************************************************

 Grp-B 8].

**************************************************

//===================================================================
//Assignment No :B(8)
//Title : Develop a network based application by setting IP address on  BeagleBoard/ARM Cortex A5.
//Roll No :
//Batch : 
//===================================================================

#!/usr/bin/python 
import socket, struct, fcntl
import ftplib

IP_ADDR          = "192.168.2.180" 

SIOCSIFADDR     = 0x8916
SIOCGIFADDR     = 0x8915
 
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
#================================================================ 
def setIpAddr(iface, ip):
     bin_ip = socket.inet_aton(ip)
     ifreq = struct.pack('16sH2s4s8s', iface, socket.AF_INET, '\x00'*2, bin_ip, '\x00'*8)
     fcntl.ioctl(sock, SIOCSIFADDR, ifreq)
     return
#=================================================================     
def getIpAddr(iface = 'eth0'):
     ifreq = struct.pack('16sH14s', iface, socket.AF_INET, '\x00'*14)
     try:
         res = fcntl.ioctl(sock, SIOCGIFADDR, ifreq)
     except:
         return None   
     ip = struct.unpack('16sH2x4s8x', res)[2]
     return socket.inet_ntoa(ip)
#===================================================================
print "Current IP Address: %s" % getIpAddr('eth0')
print "Setting IP to: %s" % IP_ADDR   
setIpAddr('eth0', IP_ADDR)
print "New IP Address: %s" % getIpAddr('eth0')

Output

root@beaglebone:/home/debian/Desktop# ifconfig 
eth0      Link encap:Ethernet  HWaddr 6c:ec:eb:5c:3d:27   
          inet addr:192.168.0.125  Bcast:192.168.0.255  Mask:255.255.255.0 
          UP BROADCAST MULTICAST  MTU:1500  Metric:1 
          RX packets:0 errors:0 dropped:0 overruns:0 frame:0 
          TX packets:0 errors:0 dropped:0 overruns:0 carrier:0 
          collisions:0 txqueuelen:1000 
          RX bytes:0 (0.0 B)  TX bytes:0 (0.0 B) 
          Interrupt:40 

lo        Link encap:Local Loopback   
          inet addr:127.0.0.1  Mask:255.0.0.0 
          inet6 addr: ::1/128 Scope:Host 
          UP LOOPBACK RUNNING  MTU:65536  Metric:1 
          RX packets:5 errors:0 dropped:0 overruns:0 frame:0 
          TX packets:5 errors:0 dropped:0 overruns:0 carrier:0 
          collisions:0 txqueuelen:0 
          RX bytes:460 (460.0 B)  TX bytes:460 (460.0 B) 

usb0      Link encap:Ethernet  HWaddr 1e:42:cc:e3:d9:72   
          inet addr:192.168.7.2  Bcast:192.168.7.3  Mask:255.255.255.252 
          inet6 addr: fe80::1c42:ccff:fee3:d972/64 Scope:Link 
          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1 
          RX packets:711 errors:0 dropped:0 overruns:0 frame:0 
          TX packets:515 errors:0 dropped:0 overruns:0 carrier:0 
          collisions:0 txqueuelen:1000 
          RX bytes:75258 (73.4 KiB)  TX bytes:94898 (92.6 KiB) 


root@beaglebone:/home/debian/Desktop# python B08_setIPnFTP.py 
Current IP Address: 192.168.0.125 
Setting IP to: 192.168.2.180 
New IP Address: 192.168.2.180 
root@beaglebone:/home/debian/Desktop# ifconfig 
eth0      Link encap:Ethernet  HWaddr 6c:ec:eb:5c:3d:27   
          inet addr:192.168.2.180  Bcast:192.168.2.255  Mask:255.255.255.0 
          UP BROADCAST MULTICAST  MTU:1500  Metric:1 
          RX packets:0 errors:0 dropped:0 overruns:0 frame:0 
          TX packets:0 errors:0 dropped:0 overruns:0 carrier:0 
          collisions:0 txqueuelen:1000 
          RX bytes:0 (0.0 B)  TX bytes:0 (0.0 B) 
          Interrupt:40 

lo        Link encap:Local Loopback   
          inet addr:127.0.0.1  Mask:255.0.0.0 
          inet6 addr: ::1/128 Scope:Host 
          UP LOOPBACK RUNNING  MTU:65536  Metric:1 
          RX packets:5 errors:0 dropped:0 overruns:0 frame:0 
          TX packets:5 errors:0 dropped:0 overruns:0 carrier:0 
          collisions:0 txqueuelen:0 
          RX bytes:460 (460.0 B)  TX bytes:460 (460.0 B) 

usb0      Link encap:Ethernet  HWaddr 1e:42:cc:e3:d9:72   
          inet addr:192.168.7.2  Bcast:192.168.7.3  Mask:255.255.255.252 
          inet6 addr: fe80::1c42:ccff:fee3:d972/64 Scope:Link 
          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1 





**************************************************

 Grp-B 10].

**************************************************



#include<stdio.h>
#include<omp.h>
 int main()
{
//creat one array 
int a[10];

//assign value to array
#pragma omp parallel for
for(int i=0;i<10;i++)
 a[i]=i+1;

//first print array values
#pragma omp parallel for
for(int i=0;i<10;i++)
 printf("%d\n",a[i]);


//implmentation of reader
//parallle reader logic 

#pragma omp parallel num_threads(5) shared(a)
{
    int tid=omp_get_thread_num();

    printf("Thread id %d is reading data %d \n",tid,a[tid]);   
   

    //just to extend do this for all threads
   
    if(tid==4)
            {
    #pragma omp parallel for
    for(int i=tid;i<10;i++)
        printf("thread havind id %d read data %d\n",tid,a[i]);
            }

}


//writing logic start here

int semaphore=0;
int cnt=0;

while(cnt<5)
{

   
    #pragma omp parallel num_threads(5) shared(a) shared(semaphore)
{
   
   
        int tid=omp_get_thread_num();
       
        if(semaphore==0)
        {
            semaphore=1;
            printf("thread %d is writing\n",tid);
            //sleep(2);
            printf("thread id %d writing is done\n",tid);
            semaphore=0;
            cnt++;
        }   
        else
        {
            printf("access denied %d \n",tid);
        }
           
}

}

return 0;
}

-------------------------------------output-----------------------------------------------
gescoe@gescoe-OptiPlex-3010:~$ cd Desktop/
gescoe@gescoe-OptiPlex-3010:~/Desktop$ sudo g++ -c rw.cpp -o rw.o -fopenmp
[sudo] password for gescoe: 
gescoe@gescoe-OptiPlex-3010:~/Desktop$ g++ -c rw.cpp -o reader.o -fopenmp -lpthread
gescoe@gescoe-OptiPlex-3010:~/Desktop$ g++ reader.o -o reader -fopenmp -lpthread 
gescoe@gescoe-OptiPlex-3010:~/Desktop$ ./reader
1
2
3
4
5
6
9
10
7
8
Thread id 2 is reading data 3 
Thread id 0 is reading data 1 
Thread id 1 is reading data 2 
Thread id 4 is reading data 5 
thread havind id 4 read data 5
thread havind id 4 read data 6
thread havind id 4 read data 7
thread havind id 4 read data 8
thread havind id 4 read data 9
thread havind id 4 read data 10
Thread id 3 is reading data 4 
thread 2 is writing
access denied 4 
access denied 3 
access denied 0 
thread id 2 writing is done
access denied 1 
thread 4 is writing
thread id 4 writing is done
access denied 0 
access denied 3 
access denied 2 
access denied 1 
thread 4 is writing
thread id 4 writing is done
access denied 0 
access denied 2 
access denied 3 
access denied 1 
thread 4 is writing
thread id 4 writing is done
access denied 0 
access denied 3 
access denied 1 
access denied 2 
thread 3 is writing
thread id 3 writing is done
access denied 0 
access denied 2 
access denied 4 
access denied 1 
gescoe@gescoe-OptiPlex-3010:~/Desktop$ 



**************************************************

 Grp-C 1].

**************************************************

#--------------------------------------------------------------------------------------
#Group             : C
#Assignment No         : 1
#Title             : Develop Robotics(stepper motor) Application using                       Beagle Board.
#Roll No             :
#Batch             : 
#---------------------------------------------------------------------------------------
#=============================================================================================

#!/usr/bin/python 
import sys
import os
import time
#=============================================================================================
LED_9    =    (0 * 32) + 30        #GPIO0_30
LED_10    =    (2 * 32) + 2        #GPIO2_2
LED_11    =    (1 * 32) + 28        #GPIO1_28
LED_12    =    (2 * 32) + 3        #GPIO2_3

STEPPER_1   =    LED_9
STEPPER_2   =    LED_10
STEPPER_3   =    LED_11
STEPPER_4   =    LED_12
#=============================================================================================
SYSFS_GPIO_DIR = "/sys/class/gpio"
#=============================================================================================
def gpioUnexport (gpio):
    try: 
           fo = open(SYSFS_GPIO_DIR + "/unexport","w")  
           fo.write(gpio)
           fo.close()
           return
       except IOError:
         return
#=============================================================================================                
def gpioExport (gpio): 
    try:
           fo = open(SYSFS_GPIO_DIR + "/export","w")  
           fo.write(gpio)
           fo.close()
           return
       except IOError:
                return
#=============================================================================================
def gpioSetDir (gpio, flag):
    try: 
           fo = open(SYSFS_GPIO_DIR + "/gpio" + gpio + "/direction" ,"w")  
           fo.write(flag)
           fo.close()
           return
     except IOError:
                return
#=============================================================================================
def gpioSetVal (gpio, val):
    try: 
        fo = open(SYSFS_GPIO_DIR + "/gpio" + gpio + "/value" ,"w")  
        fo.write(val)
        fo.close()
        return
    except IOError:
                return
#=============================================================================================

def stepperExit (gpio):
    gpioSetVal(gpio, val="0")
    gpioUnexport(gpio)
    return 
#=============================================================================================   
def stepperInit (gpio):
    gpioExport(gpio)
    gpioSetDir(gpio, flag="out")
     gpioSetVal(gpio, val="0")
     return
#=============================================================================================    
def stepperOn (gpio):
    gpioSetVal(gpio, val="1")
    return 
#=============================================================================================   
def stepperOff (gpio):
    gpioSetVal(gpio, val="0")
    return 
#=============================================================================================
def stepperInitAll():
    stepperInit(str(STEPPER_1))
    stepperInit(str(STEPPER_2))
    stepperInit(str(STEPPER_3))
    stepperInit(str(STEPPER_4))
#=============================================================================================
def stepperExitAll():
    stepperExit(str(STEPPER_1))
    stepperExit(str(STEPPER_2))
    stepperExit(str(STEPPER_3))
    stepperExit(str(STEPPER_4))
    print "\n=== Demonstration END ===\n"
    return   
#=============================================================================================
def stepperSeq5():
    stepperOn(str(STEPPER_1))
    time.sleep(0.0001)
    stepperOff(str(STEPPER_2))
    time.sleep(0.0001)
    stepperOn(str(STEPPER_3))
    time.sleep(0.0001)
    stepperOff(str(STEPPER_4))
    time.sleep(0.0001)
    return 
#=============================================================================================
def stepperSeq9():
    stepperOn(str(STEPPER_1))
    time.sleep(0.0001)
    stepperOff(str(STEPPER_2))
    time.sleep(0.0001)
    stepperOff(str(STEPPER_3))
    time.sleep(0.0001)
    stepperOn(str(STEPPER_4))
    time.sleep(0.0001)
    return 
#=============================================================================================
def stepperSeq10():
    stepperOff(str(STEPPER_1))
    time.sleep(0.0001)
    stepperOn(str(STEPPER_2))
    time.sleep(0.0001)
    stepperOff(str(STEPPER_3))
    time.sleep(0.0001)
    stepperOn(str(STEPPER_4))
    time.sleep(0.0001)
    return 
#=============================================================================================
def stepperSeq6():
    stepperOff(str(STEPPER_1))
    time.sleep(0.0001)
    stepperOn(str(STEPPER_2))
    time.sleep(0.0001)
    stepperOn(str(STEPPER_3))
    time.sleep(0.0001)
    stepperOff(str(STEPPER_4))
    time.sleep(0.0001)
    return 
#=============================================================================================   
def stepperDirLeft():
    stepperSeq5()
    time.sleep(0.01)
    stepperSeq9()
    time.sleep(0.01)
    stepperSeq10()
    time.sleep(0.01)
    stepperSeq6()
    time.sleep(0.01)
    return
#=============================================================================================
def stepperDirRight():
    stepperSeq6()
    time.sleep(0.01)
    stepperSeq10()
    time.sleep(0.01)
    stepperSeq9()
    time.sleep(0.01)
    stepperSeq5()
    time.sleep(0.01)
    return
#=============================================================================================
try:
    print "\nStepper Motor Driver using Python\n"
    print  "-----------------------------------------------\n"    
    stepperInitAll()
    while True:
        for i in range(0, 12):
            stepperDirLeft()
        time.sleep(3)
        for i in range(0, 12):
            stepperDirRight()
        time.sleep(3)
       
    stepperExitAll
    exit()
except KeyboardInterrupt:
    stepperExitAll()   
    print "Program Exit due to CTRL-C"
    exit()
        sys.exit(0)


************
output
************



/* OUTPUT

administrator@administrator-OptiPlex-390:~$ ssh root@192.168.7.2
Debian GNU/Linux 7

BeagleBoard.org BeagleBone Debian Image 2014-04-23

Last login: Wed Apr 23 20:20:41 2014 from administrator-optiplex-390.local
root@beaglebone:~# cd /home/debian/Desktop/
root@beaglebone:/home/debian/Desktop# ls
16 a.out elevator hello.c liftpins.py te22
stepper.py abc.cpp elevator.cpp hello123 liftpins.pyc te24
Te25 asd elevator.py kkk.py main te25
a e1.py gpio.py lift main.c
a.c ele gpio.pyc lift.cpp prasad
root@beaglebone:/home/debian/Desktop# python stepper.py

Stepper Motor Driver using Python

-----------------------------------------------


^C
[1]+ Stopped python stepper.py
root@beaglebone:/home/debian/Desktop#

*/








**************************************************

 Grp-C 3].

**************************************************



#include <iostream>

using namespace std;

#define BLOCK_SIZE 16

__global__ void gpuMM(float *A, float *B, float *C, int N)
{
    // Matrix multiplication for NxN matrices C=A*B
    // Each thread computes a single element of C
    int row = blockIdx.y*blockDim.y + threadIdx.y;
    int col = blockIdx.x*blockDim.x + threadIdx.x;

    float sum = 0.f;
    for (int n = 0; n < N; ++n)
        sum += A[row*N+n]*B[n*N+col];

    C[row*N+col] = sum;
}


void matmul(int a[10][10],int b[10][10])
{
    int c,d,k,m,q,p;
    int ans[10][10];
    int sum=0;
    for (c = 0; c < 10; c++) {
          for (d = 0; d < 10; d++) {
            for (k = 0; k < 10; k++) {
              sum = sum + a[c][k]*b[k][d];
            }

            ans[c][d] = sum;
            sum = 0;
          }
        }

        cout<<"Product of entered matrices:-\n";

        for (c = 0; c < 10; c++) {
          for (d = 0; d < 10; d++)
            cout<<ans[c][d]<<"\t";

          //cout<<"\n");
        }}

int main(int argc, char *argv[])
{
    // Perform matrix multiplication C = A*B
    // where A, B and C are NxN matrices
    // Restricted to matrices where N = K*BLOCK_SIZE;
    int N,K;
    K = 100;
    N = K*BLOCK_SIZE;

    cout << "Executing Matrix Multiplcation" << endl;
    cout << "Matrix size: " << N << "x" << N << endl;

    // Allocate memory on the host
    float *hA,*hB,*hC;
    hA = new float[N*N];
    hB = new float[N*N];
    hC = new float[N*N];

    // Initialize matrices on the host
    for (int j=0; j<N; j++){
        for (int i=0; i<N; i++){
            hA[j*N+i] = 2.f*(j+i);
            hB[j*N+i] = 1.f*(j-i);
        }
    }

    // Allocate memory on the device
    int size = N*N*sizeof(float);    // Size of the memory in bytes
    float *dA,*dB,*dC;
    cudaMalloc(&dA,size);
    cudaMalloc(&dB,size);
    cudaMalloc(&dC,size);

    dim3 threadBlock(BLOCK_SIZE,BLOCK_SIZE);
    dim3 grid(K,K);

    // Copy matrices from the host to device
    cudaMemcpy(dA,hA,size,cudaMemcpyHostToDevice);
    cudaMemcpy(dB,hB,size,cudaMemcpyHostToDevice);


    //cpu array
    int a[10][10],b[10][10],c[10][10];
    for(int i=0;i<10;i++)
    {
        for(int j=0;j<10;j++)
        {
                a[i][j]=b[i][j]=j+i+2;
                c[i][j]=0;
        }
    }


    //Execute the matrix multiplication kernel

    gpuMM<<<grid,threadBlock>>>(dA,dB,dC,N);
    matmul(a,b);
    // Now do the matrix multiplication on the CPU
    float sum;
    for (int row=0; row<N; row++){
        for (int col=0; col<N; col++){
            sum = 0.f;
            for (int n=0; n<N; n++){
                sum += hA[row*N+n]*hB[n*N+col];
            }
            hC[row*N+col] = sum;
        }
    }

    // Allocate memory to store the GPU answer on the host
    float *C;
    C = new float[N*N];

    // Now copy the GPU result back to CPU
    cudaMemcpy(C,dC,size,cudaMemcpyDeviceToHost);

    // Check the result and make sure it is correct
    for (int row=0; row<N; row++){
        for (int col=0; col<N; col++){
            if ( C[row*N+col] != hC[row*N+col] ){
                cout << "Wrong answer!" << endl;
                row = col = N;
            }
        }
    }

    cout << "Finished." << endl;

}