RSS

Windows Graphics & OpenGL

Introduction to C++ OpenGL Programming:

Welcome to another fine lesson in C++! Today you'll be introduced to the wonderful world of OpenGL. OpenGL is a fairly straight forward -- although at many times confusing -- concept. OpenGL gives the programmer an interface with the graphics hardware. OpenGL is a low-level, widely supported modeling and rendering software package, available on all platforms. It can be used in a range of graphics applications, such as games, CAD design, or modeling (to name a few).

OpenGL is the core graphics rendering option for many 3D games, such as Quake 3. The providing of only low-level rendering routines is fully intentional because this gives the programmer a great control and flexibility in his applications. These routines can easily be used to build high-level rendering and modeling libraries. The OpenGL Utility Library (GLU) does exactly this, and is included in most OpenGL distributions!

Unlike DirectX, OpenGL is only a graphics API; it doesn't include support for functionality such as sound, input, or networking (or anything not related to graphics). That's ok, however, because in future tutorials I will teach you how you how to use DirectX for these things.

OpenGL was originally developed in 1992 by Silicon Graphics, Inc, (SGI) as a multi-purpose, platform independent graphics API. Since 1992 all of the development of OpenGL has been headed by the OpenGL Architecture Review Board (ARB). This exclusive board is composed of the major graphics vendors and industry leaders. Some of these are Intel, IBM, NVIDIA, Microsoft, and Silicon Graphics.

OpenGL is a collection of several hundred functions that provide access to all of the features that your graphics hardware has to offer. Internally it acts like a state machine-a collection of states that tell OpenGL what to do. Using the API you can set various aspects of this state machine, including current color, blending, lighting effect, etc.

This is a very general introduction to OpenGL, and you may find other in-depth introductions elsewhere. There is a reason, however, to my generalized introduction. I don't want to slam you with specifics, but give you an idea as to what OpenGL is so that you may decide for yourself if this set of lessons is for you.


OpenGL vs. DirectX: A Comparison:

The competition between OpenGL and DirectX is possibly as well known as the wars waged between AMD and Intel enthusiasts. This topic has sparked the fires of many flame wars throughout the years, and I don't anticipate that changing anytime soon. I won't preach why I prefer OpenGL over DirectX, but rather lay out the facts and let you make that decision. So let's dive in!

Perhaps the most obvious difference is that DirectX, as opposed to OpenGL, is more than just a graphics API. DirectX contains tools to deal with such components of a game as sound, music, input, networking, and multimedia. On the other hand, OpenGL is strictly a graphics API. So what aspect of OpenGL sets it apart from the DirectX graphics component?

Well, first things first: both APIs rely on the use of the traditional graphics pipeline. This is the same pipeline that has been used in computer games since the early days of computer graphics. Although it has been modified in slight ways to adapt with advancements in hardware, the basic idea remains intact.

Both OpenGL and DirectX describe vertices as a set of data consisting of coordinates in space that define the vertex location and any other vertex related data. Graphics primitives, such as points, lines, and triangles, are defined as an ordered set of vertices. There is a difference in how each API handles how vertices are combined to form primitives.

There are a bunch of differences in the DirectX and OpenGL APIs, so I will list a few of those for you. This chart is based off the book, OpenGL Game Programming and a few of these may now be incorrect as new DirectX versions are released. If you wish to correct me, please do via one of the ways listed at the end of this tutorial.

Table 1.1:
Feature: OpenGL DirectX
Vertex Blending N/A Yes
Multiple Operating Systems Yes No
Extension Mechanism Yes Yes
Development Multiple member Board Microsoft
Thorough Specification Yes No
Two-sided lighting Yes No
Volume Textures Yes No
Hardware independent Z-buffers Yes No
Accumulation buffers Yes No
Full-screen Antialiasing Yes Yes
Motion Blur Yes Yes
Depth of field Yes Yes
Stereo Rendering Yes No
Point-size/line-width attributes Yes No
Picking Yes No
Parametric curves and surfaces Yes No
Cache geometry Display Lists Vertex Buffers
System emulation Hardware not present Let app determine
Interface Procedure calls COM
Updates Yearly Yearly
Source Code Sample SDK Implementation

So now you know what separates DirectX and OpenGL, and hopefully you have chosen based on facts which you would prefer, not on myths or opinions.


Introduction to Windows Programming and OpenGL:



At this time we will take a look into the vast world of Windows programming. Since this tutorial is based entirely on programming done within the Windows environment, it will be required of you to have access to a Windows machine and compiler such as Code::Blocks.


For the programs we will be creating you will need a base understanding of the mechanics and structuring of the Windows operating system. Not to worry, however, because I am going to teach this to you!

Microsoft Windows is a multi-tasking operating system that allows multiple applications, referred to here on out as processes. Every process in Windows is given a certain amount of time, called a time slice, where the application is given the right to control the system without being interrupted by the other processes. The runtime priority and the amount of time allocated to a process are determined by the scheduler.

The scheduler is, simply put, the manager of this multi-tasking operating system, ensuring that each process is given the time and the priority it needs depending on the current state of the system.

When it comes to game developers, you will find a large common interest in multithreading. Processes can be broken down into threads, where each thread can execute its own code to allow for multitasking within a single application. The scheduling for threads is the same as that for processes, except that threads are what make up the process.

This means that within your games you can have multiple threads running that can perform multiple calculations at once and thus provide your game with multitasking within itself. To go a step farther we can do a quick explanation of fibers. In newer versions of Windows (Windows 98+) there is an even lower level execution object exists, called a fiber. Each thread in your process has the ability to house multiple fibers that can perform multiple operations at once, all in a single thread.

Windows is what is known as an event-driven operating system. What this means is that each process is executed based on the events they receive from the operating system. For instance, an application may sit at idle and wait for the user to press a key. When that key is pressed Windows will register an event to the application that the key is down.

Windows programming is difficult at all in most cases, and to start we'll use the most basic program ever created. Hello World is used in almost every class when you begin programming in any language, and that won't change here. So, shall we have a look at Hello World in Windows style? Sure!


#include  int APIENTRY WinMain(HINSTANCE hInstance,                      HINSTANCE hPrevInstance,                      LPSTR     lpCmdLine,                      int       nCmdShow) {     MessageBox(NULL, "\tHello World!", "My first windows app", NULL);  return 0; }


As you can see, it's pretty straight forward. Don't pay attention to the things that don't make sense, as in the next lesson we will go in-depth to explain WinMain () and other functions, as well as show how this and OpenGL work together!


WinMain() and the Windows Procedure:

Every Windows programming needs a main entry point. That being said, you may be wondering what this entry point is. The main entry point for any Windows program is called WinMain. The function prototype for WinMain is a little confusing at first, but as we continue to work with it you'll notice it becomes much easier to understand. Well. we've told you what it is; now were going to show you! Here's the prototype for WinMain:

int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nShowCmd);


As you may have already noticed, the return type for WinMain is, and always will be, int. All 32-bit Windows operating system uses the calling convention WINAPI. This calling convention MUST be used to distinguish the function as the entry point. Now for the parameters. As you can see, WinMain uses four parameters when the program starts. Let's have a look at them, shall we?
hInstance - is a handle to your applications instance, where an instance  can be considered to be a single run of your application. The instance  is used by windows as a reference to your application for event handling, message processing, and various other duties. hPrevInstance - is always NULL.  lpCmdLine - is a pointer string that is used to hold any command-line arguments that may have been specified when the application began.   For example, if the user opened the Run application and typed myapp.exe myparameter 1, then lpCmdLine would be myparameter 1. nShowCMD - is the parameter that determines how your application's window will be displayed once it begins executing. 
Pretty simple, right? Don't worry if it's confusing, it will make sense soon enough! The Windows program you create is going to need some way to handle the messages that Windows will send to it. A few examples of these messages are: WM_CREATE, WM_SIZE, and WM_MOVE. There are TONS of these messages, and we'll show you how to handle a large number of them. To allow Windows to communicate with your application, we'll create a dandy little function called a Windows procedure. This most common name for this function is WndProc. This function MUST be created and used to determine how your application will respond to various events. The Windows procedure may also be called the event handler because, well, it responds to Windows events! So let's have a quick look at the prototype:
LRESULT CALLBACK WndProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam); 
This function is declared with a return type of LRESULT CALLBACK. The LRESULT type is used by Windows to declare a long integer, and CALLBACK is a calling convention used with functions that are called by Windows. The Windows Procedure is a function pointer, which allows you to call it whatever you want because the function's address will be assigned as a function pointer upon creation of the window class.
hwnd - Only important if you have several windows of the same class open at one time. This is used to determine which window hwnd pointed to before  deciding on an action. message - The actual message identifier that WndProc will be handling. wParam and lParam - Extensions of the message parameter. Used to give  more information and point to specifics that message cannot on its own. 
Well now you should have a better understanding of these two topics. You may be wondering when you get to see some openGL usage, and the answer is soon. We first need to cover the basics, let's remember, we're here to learn!


First Windows Application:


The following code is a build up on the basic "hello world" program I showed you earlier. Take a minute to review it, maybe even key it into your compiler and run it, and then we will break it down so that it is easier to understand what is actually going on.

/* Trim fat from windows*/ #define WIN32_LEAN_AND_MEAN  #pragma comment(linker, "/subsystem:windows") /* Pre-processor directives*/ #include "stdafx.h" #include  /* Windows Procedure Event Handler*/ LRESULT CALLBACK WndProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam) {  PAINTSTRUCT paintStruct;  /* Device Context*/  HDC hDC;   /* Text for display*/  char string[] = "Hello, World!";   /* Switch message, condition that is met will execute*/  switch(message)  {   /* Window is being created*/   case WM_CREATE:     return 0;    break;   /* Window is closing*/   case WM_CLOSE:     PostQuitMessage(0);    return 0;    break;   /* Window needs update*/   case WM_PAINT:     hDC = BeginPaint(hwnd,&paintStruct);    /* Set txt color to blue*/    SetTextColor(hDC, COLORREF(0x00FF0000));    /* Display text in middle of window*/    TextOut(hDC,150,150,string,sizeof(string)-1);    EndPaint(hwnd, &paintStruct);    return 0;    break;   default:    break;  }  return (DefWindowProc(hwnd,message,wParam,lParam)); } /* Main function*/ int APIENTRY WinMain(HINSTANCE hInstance,                      HINSTANCE hPrevInstance,                      LPSTR     lpCmdLine,                      int       nCmdShow) {  WNDCLASSEX  windowClass;  //window class  HWND  hwnd;    //window handle  MSG   msg;    //message  bool  done;    //flag saying when app is complete  /* Fill out the window class structure*/  windowClass.cbSize = sizeof(WNDCLASSEX);  windowClass.style = CS_HREDRAW | CS_VREDRAW;  windowClass.lpfnWndProc = WndProc;  windowClass.cbClsExtra = 0;  windowClass.cbWndExtra = 0;  windowClass.hInstance = hInstance;  windowClass.hIcon = LoadIcon(NULL, IDI_APPLICATION);  windowClass.hCursor = LoadCursor(NULL, IDC_ARROW);  windowClass.hbrBackground = (HBRUSH)GetStockObject(WHITE_BRUSH);  windowClass.lpszMenuName = NULL;  windowClass.lpszClassName = "MyClass";  windowClass.hIconSm = LoadIcon(NULL, IDI_WINLOGO);  /* Register window class*/  if (!RegisterClassEx(&windowClass))  {   return 0;  }  /* Class registerd, so now create window*/  hwnd = CreateWindowEx(NULL,  //extended style   "MyClass",   //class name   "A Real Win App",  //app name   WS_OVERLAPPEDWINDOW |  //window style   WS_VISIBLE |   WS_SYSMENU,   100,100,   //x/y coords   400,400,   //width,height   NULL,    //handle to parent   NULL,    //handle to menu   hInstance,   //application instance   NULL);    //no extra parameter's  /* Check if window creation failed*/  if (!hwnd)   return 0;  done = false; //initialize loop condition variable  /* main message loop*/  while(!done)  {   PeekMessage(&msg,NULL,NULL,NULL,PM_REMOVE);   if (msg.message == WM_QUIT) //check for a quit message   {    done = true; //if found, quit app   }   else   {    /* Translate and dispatch to event queue*/    TranslateMessage(&msg);     DispatchMessage(&msg);   }  }  return msg.wParam; } 
Well isn't this a whole mess of code! The first thing that you may have noticed is #define WIN32_LEAN_AND_MEAN. This syntax prevents Visual C++ from linking modules that you aren't going to need in your application.

Moving on we come to the include line #include . This includes all the headers you need in this application. Sometimes you may want to include , which will give you a few useful macros to use in Windows development.

The first function we arrive at is the WndProc function. We've discussed this before, so I am just going to highlight two lines I have added here.
HDC hDC;    //device context Char string[] = "Hello World!"; //display text 
These two lines are essential as they declare the device context that we are going to use to output to the window we create, and the string that we will display. As we continue on in the code we arrive at the switch statement. This switch is used to determine the message being passed to the windows procedure. In this particular instance we want to take a closer look at the WM_PAINT block.
case WM_PAINT:     hDC = BeginPaint(hwnd,&paintStruct);    /* Set txt color to blue*/    SetTextColor(hDC, COLORREF(0x00FF0000));    /* Display text in middle of window*/    TextOut(hDC,150,150,string,sizeof(string)-1);    EndPaint(hwnd, &paintStruct);    return 0;    break; 
When the window is moved, resized, or is otherwise changed the window needs to be updated. The first noticeable change here is the use of the hDC device context. The win32 function BeginPaint() returns the graphics device context for the hwnd passed to it. You can then use this hDC to set the text color with SetTextColor() and follow up with the TextOut() function to display the text. If you want to know more about these functions, check out MSDN.

Next function up is the WinMain() function. Most of the WinMain() content is pretty straight forward, but were going to review a few parts of it for good measure. The msg variable holds the message received by PeekMessage() from the queue, and will be sent to TranslateMessage() and DispatchMessage(). The variable done is a Boolean value used by your message loop and will not equal true until a WM_QUIT message has been received from the queue to indicate that the application is about to be closed.

For easier understanding we will break the order of each setup task into a list.
1. Window-class setup 2. Window-class registration 3. Window Creation 4. Message loop with event handler 
We now have a fully working Windows application! I encourage you to toy around with the code and alter it to your liking. Don't be discouraged by errors or problems, for it is these things that make us better.



WGL and the Wiggle Functions in C++:



The simple fact that OpenGL is only a graphics API means that any user interaction, or things like screen and window issues needs to be handled by the operating system. Most operating systems come with a set of extensions that tie OpenGL together with user interaction and window management. This tends to make our lives a little bit easier, but only if we know how to take advantage of this option. In Windows this set of functions are called the wiggle functions. Each of these functions is prefixed with wgl.

To maintain the portability of OpenGL, each operating system must supply functionality for specifying the rendering window before OpenGL can use it. In Windows the Graphics Device Interface uses a device context to remember settings about drawing modes and commands, but in OpenGL the rendering context is used to remember these things. You need to remember, however, that the device context is not a rendering context. The device context MUST be specified in a GDI call, unlike a rendering context, which is specified in an OpenGL call.

If you wish to render more than one window at once, multiple rendering contexts are allowed. You must ensure, however, that the proper rendering context is being used on the proper window. Another thing to remember is that OpenGL is thread-safe. You can have multiple threads rendering to the same device context at one time.

As I mentioned to you earlier, wiggle functions bring Windows API support into OpenGL. Well let's take this time to have a look at a few common wiggle functions:
  • wglCreateContext();
  • wglDeleteContext();
  • wglMakeCurrent();
The wglCreateContext() function creates a handle to the OpenGL rendering context while being passed like a handle to a GDI device context. The correct prototype for this function is:
 HGLRC wglCreateContext(HDC hDC); 
This function should only be called after the pixel format for the device context has been set. Don't worry, pixel format is coming into teaching shortly.

Keep in mind that as with a device context, a rendering context must be deleted after you are finished with it. This is where the wglDeleteContext() function comes into play. Let's have a look at the prototype for good measure:
 BOOL  wglDeleteContext(HGLRC hRC); 
The name wglMakeCurrent() is highly accurate to what the function does. The function makes the rendering context passed to it the current rendering context. Makes a lot of sense, doesn't it? The device context used must have the same pixel format characteristics as the device context that was used to create the rendering context. This means that the device context used to create the rendering context does not need to be the same as the device context assigned to the wglMakeCurrent() function. Without further delay, let's see the prototype!
 BOOL  wglMakeCurrent(HDC hDC, HGLRC hRC); 
You need to ensure that the device context and the rendering context passed to the function have the same pixel format, or the function will not work. To deselect the rendering context you can simply pass NULL for the hRC parameter, or simply pass another rendering context.

Both the wglCreateContext() and the wglMakeCurrent() functions should be called upon window creation. Let's look at a code snippet for an example of these in use:
LRESULT CALLBACK WndProc (HWND hwnd, UNIT message, WPARAM wParam, LPARAM lParam) {  static HGLRC hRC; //rendering context  static HDC hDC; //device context  switch (message)  {  case WM_CREATE:  hDC = GetDC(hwnd); //get the device context for window  hRC = wglCreateContext(hDC); //create rendering context  wglMakeCurrent(hDC,hRC); //make rendering context current  break;  case WM_DESTROY:  wglMakeCurrent(hDC,NULL); //deselect rendering context  wglDeleteContext(hRC);  //delete rendering context  PostQuitMessage(0);  //send wm_quit  break;  } } 
This code creates and destroys your OpenGL window.

  • Digg
  • Del.icio.us
  • StumbleUpon
  • Reddit
  • RSS

DOTNET

The .NET Framework is a managed type-safe environment for application development and execution. The .NET Framework manages all aspects of your program’s execution. It allocates memory for the storage of data and instructions, grants or denies the appropriate permissions to your application, initiates and manages application execution, and manages the reallocation of memory from resources that are no longer needed. The .NET Framework consists of two main components: the common language runtime (CLR)[equivalent to JRE] and the .NET Framework class library.

CLR : --The common language runtime can be thought of as the environment that manages code execution. It provides core services, such as code compilation, memory allocation, thread management, and garbage collection. Through the common type system (CTS), it enforces strict type-safety and ensures that code is executed in a safe environment by also enforcing code access security.

The .NET Framework class library provides a collection of useful and reusable types that are designed to integrate with the CLR. The types provided by the .NET Framework are object-oriented and fully extensible.

The .NET Framework is designed for cross-language compatibility, which means, simply, that .NET components can interact with each other no matter what supported language they were written in originally. So, an application written in Microsoft Visual Basic .NET might reference a dynamic-link library (DLL) file written in Microsoft Visual C#.

This level of cross-language compatibility is possible because of the CLR. When a .NET application is compiled, it is converted from the language in which it was written (Visual Basic .NET, C#, or any other .NET-compliant language) to Microsoft Intermediate Language (MSIL or IL)[equivalent to bytecode]. MSIL is a low-level language that the CLR can read and understand. Because all .NET executables and DLLs exist as MSIL, they can freely interoperate.
The Common Language Specification (CLS) defines the minimum standards to which .NET language compilers must conform.

The CTS ensures type compatibility between .NET components. Because .NET applications are converted to IL prior to deployment and execution, all primitive data types are represented as .NET types. Thus, a Visual Basic Integer and a C# int are both represented in IL code as a System.Int32. Because both languages use a CTS, it is possible to transfer data between components and avoid time-consuming conversions or hard-to-find errors.

The Structure of a .NET Application
---------------------------------------------
The primary unit of a .NET application is the assembly. An assembly is a self-describing collection of code, resources, and metadata. The assembly manifest contains information about what is contained within the assembly. An assembly contains one or more modules. A module contains the code that makes up your application or library, and it contains metadata that describes that code. When you compile a project into an assembly, your code is converted from high-level code to IL. Because all managed code is first converted to IL code, applications written in different languages can easily interact. Each module also contains a number of types. Types are templates that describe a set of data encapsulation and functionality. There are two kinds of types: reference types (classes) and value types (structures).

Each type is described to the CLR in the assembly manifest. A type can contain fields, properties, and methods, each of which should be related to a common functionality. For example, bank account(class).A field represents storage of a particular type of data. Properties are similar to fields, but properties usually provide some kind of validation when data is set or retrieved. Methods represent behavior, such as actions taken on data stored within the class or changes to the user interface.

Compilation and Execution of a .NET Application
------------------------------------------------------------
When you compile a .NET application, it is not compiled to binary machine code; rather, it is converted to IL. This is the form that your deployed application takes—one or more assemblies consisting of executable files and DLL files in IL form. At least one of these assemblies will contain an executable file that has been designated as the entry point for the application.
When execution of your program begins, the first assembly is loaded into memory. At this point, the CLR examines the assembly manifest and determines the requirements to run the program. It examines security permissions requested by the assembly and compares them with the system’s security policy. If the system’s security policy does not allow the requested permissions, the application will not run. If the application passes the system’s security policy, the CLR executes the code. It creates a process for the application to run in and begins application execution. When execution starts, the first bit of code that needs to be executed is loaded into memory and compiled into native binary code from IL by the CLR's Just-In-Time (JIT) compiler. Once compiled, the code is executed and stored in memory as native code. Thus, each portion of code is compiled only once when an application executes. Whenever program execution branches to code that has not yet run, the JIT compiler compiles it ahead of execution and stores it in memory as binary code. This way, application performance is maximized because only the parts of a program that are executed are compiled.

The .NET base class library is a collection of object-oriented types and interfaces that provide object models and services for many of the complex programming tasks you will face. Most of the types presented by the .NET base class library are fully extensible(INHERITANCE), allowing you to build types that incorporate your own functionality into your managed code.

The .NET Framework base class library contains the base classes that provide many of the services and objects you need when writing your applications. The class library is organized into namespaces[PACKAGES].
A namespace is a logical grouping of types that perform related functions. For example, the System.Windows.Forms namespace contains all the types that make up Windows forms and the controls used in those forms.
Namespaces are logical groupings of related classes. The root of the .NET Framework is the System namespace[like java in java.lang.*]. Other namespaces can be accessed with the period operator.


System: This namespace is the root for many of the low-level types required by the .NET Framework. It is the root for primitive data types as well, and it is the root for all the other namespaces in the .NET base class library.
System.Collections: This namespace contains classes that represent a variety of different container types, such as ArrayList, SortedList, Queue, and Stack. You also can find abstract classes, such as CollectionBase, which are useful for implementing your own collection functionality.
System.ComponentModel: This namespace contains classes involved in component creation and containment, such as attributes, type converters, and license providers.
System.Data: This namespace contains classes required for database access and manipulations, as well as additional namespaces used for data access.
System.Data.Common: This namespace contains a set of classes that are shared by the .NET managed data providers.
System.Data.OleDb: This namespace contains classes that make up the managed data provider for OLE DB data access.
System.Data.SQLClient: This namespace contains classes that are optimized for interacting with Microsoft SQL Server.
System.Drawing: This namespace exposes GDI+ functionality and provides classes that facilitate graphics rendering.
System.IO: In this namespace, you will find types for handling file system I/O.
System.Math: This namespace is home to common mathematics functions such as extracting roots and trigonometry.
System.Reflection: This namespace provides support for obtaining information and dynamic creation of types at runtime.
System.Security: This namespace is home to types dealing with permissions, cryptography, and code access security.
System.Threading: This namespace contains classes that facilitate the implementation of multithreaded applications.
System.Windows.Forms: This namespace contains types involved in creating standard Windows applications. Classes that represent forms and controls reside here as well.


Reference Types and Value Types

Application data memory is divided into two primary components, the stack and the heap. The stack is an area of memory reserved by the application to run the program. The heap, on the other hand, is a separate area of memory reserved for the creation of reusable objects. The CLR manages allocation of heap memory for objects and controls the reclamation of memory from unused objects through garbage collection.

All the data associated with a value type(STRUCTURE)is allocated on the stack. When a variable of a value type goes out of scope, it is destroyed and its memory is reclaimed. A variable of a reference type(CLASS), on the other hand, exists in two memory locations. The actual object data is allocated on the heap. A variable containing a pointer to that object is allocated on the stack. When that variable is called by a function, it returns the memory address for the object to which it refers. When that variable goes out of scope, the object reference is destroyed but the object itself is not. If any other references to that object exist, the object remains intact. If the object is left without any references, it is subject to garbage collection.
Examples of value types include primitives, such as Integer (int), Boolean (bool), Char (char), and so on, as well as user-defined types such as Structure (struct) and Enumeration (enum). Classes represent the majority of reference types. Other reference types include the interface, delegate, and array types.
Using Value Type and Reference Type Variables
A variable that represents a value type contains all the data represented by that type. A variable that represents a reference type contains a reference to a particular object.

The Imports and Using Statements
Visual Basic .NET
Imports System.Windows.Forms
Visual C#
using System.Windows.Forms;

Members
Classes describe the properties and behaviors of the objects they represent through members-- methods, fields, properties, and events.
Fields and properties represent the data about an object—the color of the car.
A method represents something the object can do, ---turn on headlights.
An event represents something interesting that happens to the object, such as overheating or crashing.

Classes vs. Structures
Both can contain members such as fields and methods.
Both require a constructor to create a new instance of themselves
Both inherit from Object.
The key difference between classes and structures is that classes are reference types and structures are value types. On a low level, this means that the instance data for classes is allocated on the heap, whereas the instance data for structures is allocated on the stack. Access to the stack is designed to be light and fast, but storage of large amounts of data on the stack can impede overall application performance.
Structures are best used for smaller, lightweight objects that contain relatively little instance data or for objects that do not persist for long.
Classes are best used for larger objects that contain more instance data and are expected to exist in memory for extended periods.

Methods
(Sub Procedures)
Public Sub MySub()
MessageBox.Show("WELCOME")
End Sub
(Functions)
Public Function Add(ByVal first as Integer, ByVal second as Integer) As Integer
Dim Result as Integer
Result = first + second
Return Result
End Function

Variables declared within methods are said to have method scope(local).
Variables that are not destroyed after a method finishes execution---static method variables, persist in memory and retain their values through multiple executions of a method.

Public Sub myMethod()
Static Iterations as Integer
Iterations += 1
End Sub

Parameters
A parameter is an argument that is passed to the method by the method that calls it. Parameters can be passed in two ways, by value(default) or by reference. ByVal / ByRef

Optional Parameters(default Parameters)
In Visual Basic .NET, you are able to specify optional parameters for your methods. This feature is not available in Visual C#. You specify a parameter as optional using the Optional keyword. Optional parameters must be the last parameters in a method declaration, and you must supply default values for optional parameters.
Public Sub Cook(ByVal time As Integer, Optional ByVal temp As Integer = 350)

End Sub

Constructors and Destructors
The constructor is the first method that is run when an instance of a type is created. In Visual Basic, the constructor is always Sub New. Constructors can never return a value and can be overridden to provide custom initialization functionality. A constructor can also contain calls to other methods.
Public Class A
Public Sub New()

End Sub
End Class
A destructor (known as a finalizer in Visual Basic) contains code to “clean up” when a class is destroyed. This cleanup might include decrementing counters or releasing resources. A finalizer in Visual Basic .NET is always Sub Finalize().

Public Class A
Protected Overrides Sub Finalize()

End Sub
End Class

Scope and Access Levels
Access levels define how types are instantiated and how members are accessed.
Access modifiers are keywords such as Public (public), Private (private), and Friend (internal) that precede a variable or type declaration. The keyword that is used controls the level of access the member is allowed. When a modifier precedes a type declaration, it determines both the scope of its members and how that type is instanced.
Access Modifier Effect on Members
Public (Visual Basic .NET), public (Visual C#) Can be accessed from anywhere.
Private (Visual Basic .NET), private (Visual C#) Can be accessed only by members within the type that defines it.
Friend (Visual Basic .NET), internal (Visual C#) Can be accessed from all types within the assembly, but not from outside the assembly.
Protected (Visual Basic .NET), protected (Visual C#) Can be accessed only by members within the type that defines it or types that inherit from that type.
Protected Friend (Visual Basic .NET), protected ¬internal (Visual C#) Can be accessed from all types within the assembly or from types inheriting from the owning type. This is the union of Protected (protected) and Friend (internal) access.
Any member with the
Public (public) modifier is visible to all code outside the class. Thus, other objects can access and modify public fields and can call public methods.
Private (private) methods are visible only inside the type to which they belong and cannot be accessed from the outside.
Friend (internal), indicates that members can be accessed by other types in the same assembly but cannot be accessed from types outside the assembly.
The Protected (protected) modifier allows access from within the type to which the member belongs and to any types that inherit that type.
The Protected Friend (protected internal) level provides the union of Protected (protected) and Friend (internal) access.
For member variables, the access modifier can replace the Dim statement. If the Dim statement is used (in Visual Basic .NET) or no access modifier is used (in Visual C#), the variable is
private in Visual C# and Visual Basic .NET classes,
public in Visual Basic .NET structures, and
private in Visual C# structures.
If no access modifier is specified, the method is
private (private) by default in a class or structure in C#,
public (public) in a class or structure in Visual Basic .NET.

The garbage collector continuously traces the reference tree in the background and identifies objects that no longer have references. When it finds one, it deletes it and reclaims the memory.
The garbage collector is a low-priority thread under normal circumstances. It operates when processor time is not consumed by more important tasks. When memory becomes limited, however, the garbage collector thread moves up in priority. Memory is reclaimed at a more rapid pace until it is no longer limited, at which point the priority of garbage collection is again lowered.


To add a form to your application at run time
'This example assumes that you have already designed a form called DialogForm
Dim myForm As DialogForm
myForm = New DialogForm()
To create an inherited form with the Inheritance Picker
1. From the Projects menu, select Add Inherited Form. The Add New Item dialog box opens.
2. In the left pane of the dialog box, choose Local Project Items. In the right pane, select Inherited Form. Name this form in the Name box, and click Open to open the Inheritance Picker.
3. The forms in your project are displayed in the Inheritance Picker. If the form from which you want to inherit is one of these forms, choose it and click OK. A new inherited form is added to your project.
If you want to inherit from a form outside of your project, click Browse. Navigate to the project containing the form you want. Click the DLL file containing the form, and click Open.
To create an inherited form in code
'This example assumes that you are inheriting from a form class named MainForm and that that form resides in your project
Public Class myForm
Inherits MainForm
' Additional class implementation omitted
End Class
Opacity
You can create striking visual effects for your form by altering its transparency with the Opacity property controls. Opacity values range between 0 and 1. A value of 1 indicates that a form is completely opaque, and a value of 0 creates a completely transparent form. Any value between the two settings results in a partially transparent form. An Opacity of 1 (fully opaque) is the default value. The Opacity property is useful when it is necessary to keep one form in the foreground but monitor action in a background form. Generally, a control inherits the opacity of the form that hosts it(parent).
MyForm.Opacity = .5

Form Lifetime Events
Load, Activated/Deactivate, VisibleChanged, Closing, Closed
The Load event is fired when an instance of a form is first loaded into the program. This event is raised the first time that the Form.Show or Form.ShowDialog method is called for each instance of a form.
Activated is raised whenever the form receives the focus.
The Deactivate event is raised whenever the current form loses the focus.
VisibleChanged event is raised the form is made visible or invisible. The form methods that cause this event to be raised include Form.Show, Form.ShowDialog, Form.Hide, and Form.Close.
The Closing event is raised when the current form is in the process of closing but has not yet fully closed.
The Closed event is raised after a form has been closed. Use the Closed event to provide any necessary clean-up code.

The .NET Data Types
They are value types and can be broken down into the following subcategories: Integer types, floating-point types, the Boolean type, and the Char type. Two built-in reference types, the String type and the Object type, are an integral part of your application.
Integer Types
Type Visual C# Name Visual Basic .NET Name Description Range
System.Byte byte Byte 8-bit unsigned integer 0 to 255
System.Int16 short Short 16-bit signed integer -32768 to 32767
System.Int32 int Integer 32-bit signed integer -231 to 231-1
System.Int64 long Long 64-bit signed integer -263 to 263-1
System.SByte sbyte (Not implemented) 8-bit signed integer -128 to 127
System.UInt16 ushort (Not implemented) 16-bit unsigned integer 0 to 65535
System.UInt32 uint (Not implemented) 32-bit unsigned integer 0 to 232-1
System.UInt64 ulong (Not implemented) 64-bit unsigned integer 0 to 264-1
Floating-Point Types
Type Visual C# Name Visual Basic .NET Name Description Precision Range (Approximate)
System.Single float Single 32-bit floating-point variable 7 significant digits +/- 1.4 x 10-45 to +/-3.4 x 1038
System.Double double Double 64-bit floating-point variable 15–16 significant digits +/- 5.0 x 10-324 to +/-1.7 x 10308
System.Decimal decimal Decimal 128-bit floating-point variable 28 significant digits +/- 1.0 x 10-28 to +/- 7.9 x 1028
System.Boolean
The values that are valid for Boolean variables are True and False (Visual Basic .NET) or true and false (Visual C#).
System.Char
The System.Char type represents a single instance of a 16-bit Unicode character. It is called Char in Visual Basic .NET and char in Visual C#.
System.String
is a reference type that represents a series of Char data types.
System.Object
is the supertype of all types in the .NET Framework. Every type, whether value type or reference type, derives from System.Object.
Implicit Conversions
From To
Byte (VB .NET)
byte (Visual C#) Short, Integer, Long, Single, Double, Decimal
short, ushort, int, uint, long, ulong, float, double, decimal
Short
short Integer, Long, Single, Double, Decimal
int, long, float, double, decimal
Integer
int Long, Single, Double, Decimal
long, float, double, decimal
Long
long Single, Double, Decimal
float, double, decimal
Single
float Double
double
Char
char Integer, Long, Single, Double, Decimal
int, uint, long, ulong, float, double, decimal
sbyte (Visual C# only) short, int, long, float, double, decimal
ushort (Visual C# only) int, uint, long, ulong, float, double, decimal
uint (Visual C# only) long, ulong, float, double, decimal
ulong (Visual C# only) float, double, decimal

Explicit Conversions - CType
Dim aLong As Long = 1000
Dim anInteger As Integer
anInteger = CType(aLong, Integer)

Dim anInteger As Integer = 100000
Dim aShort As Short
aShort = CType(anInteger, Short)
Option Strict in Visual Basic .NET
When Option Strict is on, strong typing is enforced and only conversions that can be performed without loss of data are allowed. When Option Strict is off, however, strong typing is not enforced and all conversions are performed implicitly. The default setting is Option Strict Off. (The primary purpose of Option Strict Off is backward compatibility with previous versions of Visual Basic.)
Option Strict On---to set it on

Using Data Type Functionality
All data types have built-in functionality. The methods are :
Equals.
Determines whether two instances are equal
GetHashCode.
Serves as a hash function for a particular type
GetType.
Returns the type object for the current instance
ToString.
Returns a human-readable form of the object
Boxing
Boxing is the implicit conversion of value types to reference types. All classes and types derive from Object, and each of these four methods is a method of the Object class. Because each class derives from Object, each class can be implicitly converted to that type. When you call one of these methods, the CLR creates a temporary reference for your value type variable and allows you to treat it as a reference type.
Dim I As Integer = 100
Dim O As Object
O = I
Parse
All of the value data types implement a Parse method. Parse is used to create a numeric value from a string. Controls that accept user input, such as TextBox, do so in the form of a string. The Parse method can be used to convert that string to usable data. In all implementations, Parse is a static (Shared) method and must be called from the type object rather than from an instance.
Dim I As Integer
Dim S As String
S = "1234"
I = Integer.Parse(S)
String Functions
Some Useful Instance String Methods
Name Description
String.Insert Inserts a specified string into the current instance
String.PadLeft, String.PadRight Adds characters to the left and right of the string, respectively
String.Remove Deletes a specified number of characters from the string, beginning at a specified character
String.Replace Replaces all occurrences of a specified character in the string with another specified character
String.Split Returns an array of substrings that are delimited by a specified character
String.Substring Returns a substring from the specified instance
String.ToCharArray Returns an array of the characters that make up the string
String.ToLower, String.ToUpper Returns the string converted to all lowercase or all uppercase, respectively
String.TrimEnd, String.TrimStart, String.Trim Removes trailing, leading, or both characters from the string, respectively

Some Useful Static (Shared) String Methods
Name Description
String.Compare Compares two specified string objects
String.Concat Returns a string that is the result of the concatenation of two or more strings
String.Format Returns a string that has been formatted according to a specified format
String.Join Returns a string that is the result of the concatenation of a specified array of strings, with a specified separation string between each member of the array

Constants allow you to assign user-friendly names to these values and refer to them in code.
Public Const Pi As Double = 3.14159265
Enumerations are user-defined sets of integral constants that correspond to a set of friendly names.
=>Public Enum DaysOfWeek
Monday = 1
Tuesday = 2
Wednesday = 3
Thursday = 4
Friday = 5
Saturday = 6
Sunday = 7
End Enum
=>Public Sub ScheduleDayOff(ByVal day As DaysOfWeek)
Select Case day
Case DaysOfWeek.Monday
' Implementation code omitted
Case DaysOfWeek.Tuesday
' Implementation code omitted
' Additional cases omitted
End Select
End Sub

=>Public Enum Numbers
zero ' equals zero
one ' equals one
two ' equals two
End Enum
=>MessageBox.Show((Numbers.two * 2).ToString()) 'Displays 4
Arrays
=>' This line declares and initializes an array of 33 integers, with indexes ranging from 0 to 32
Dim myIntegers(32) As Integer

=>' This line declares the array
Dim myIntegers() As Integer
' This line initializes the array to six members and sets their values
myIntegers = New Integer() {0,1,2,3,4,5}

=>Dim myIntegers(32) As Integer
' This line reinitializes the array
ReDim myIntegers(45)

=>' Declares the array and initializes it with four members
Dim myIntegers() As Integer = {0,1,2,3}
' Resizes the array, but retains the data in elements 0 through 3
ReDim Preserve myIntegers(10)

Multidimensional Arrays
Rectangular Arrays
-- all the rows have the same number of columns.

' Declares an array of 5 by 3 members
Dim intArrays(4, 2) As Integer
' Declares a two-dimensional array and sets initial values
Dim intArrays2( , ) As Integer = {{1, 2, 3}, {4, 5, 6}}
' Declares a cubical array and sets initial values
Dim cubeArray( , , ) As Integer = {{{7, 2}, {1, 4}}, {{3, 5}, {4, 4}}}
' Declares a complex array of 3 x 3 x 4 x 5 x 6 members
Dim complexArray(2, 2, 3, 4, 5) As Integer

Jagged Arrays
A two-dimensional jagged array can be thought of as a table where each row can have a different number of columns. A jagged array is really an array of arrays.

' Declares an array of 3 arrays
Dim Families(2)() As String
' Initializes the first array to 4 members and sets values
Families(0) = New String() {"Smith", "Mom", "Dad", "Uncle Phil"}
' Initializes the second array to 5 members and sets values
Families(1) = New String() {"Jones", "Mom", "Dad", "Suzie", "Little Bobby"}
' Initializes the third array to 3 members and sets values
Families(2) = New String() {"Williams", "Earl", "Bob"}

  • Digg
  • Del.icio.us
  • StumbleUpon
  • Reddit
  • RSS

WIRELESS NETWORKS

What is Wireless Network????

Wireless network refer to any type of computer network that is not connected by cables of any kind. It is a method by which telecommunications networks and enterprise (business), installations avoid the costly process of introducing cables into to a building, or as a connection between various equipment locations. Wireless telecommunications networks are generally implemented and administered using a transmission system called radio waves. This implementation takes place at the physical level, (layer), of the network structure.


Wireless network is a network set up by using radio signal frequency to communicate among computers and other network devices. Sometimes it’s also referred to as WiFi network or WLAN. This network is getting popular nowadays due to easy to setup feature and no cabling involved. You can connect computers anywhere in your home without the need for wires.

Here is simple explanation of how it works, let say you have 2 computers each equipped with wireless adapter and you have set up wireless router. When the computer send out the data, the binary data will be encoded to radio frequency and transmitted via wireless router. The receiving computer will then decode the signal back to binary data.

It doesn’t matter you are using broadband cable/DSL modem to access internet, both ways will work with wireless network. If you heard about wireless hotspot, that means that location is equipped with wireless devices for you and others to join the network.


The two main components are wireless router or access point and wireless clients :

If you have not set up any wired network, then just get a wireless router and attach it to cable/DSL modem. You then set up wireless client by adding wireless card to each computer and form a simple wireless network. You can also cable connect computer directly to router if there are switch ports available.

Wireless router or access points should be installed in a way that maximizes coverage as well as throughput. The coverage provided is generally referred to as the coverage cell. Large areas usually require more than one access point in order to have adequate coverage. You can also add access point to your existing wireless router to improve coverage.




Wireless Operating Mode

The IEEE 802.11 standards specify two operating modes: infrastructure mode and ad hoc mode.

Infrastructure mode is used to connect computers with wireless network adapters, also known as wireless clients, to an existing wired network with the help from wireless router or access point. The 2 examples which I specified above operate in this mode.

Ad hoc mode is used to connect wireless clients directly together, without the need for a wireless router or access point. An ad hoc network consists of up to 9 wireless clients, which send their data directly to each other.





Types of wireless connections

Wireless PAN

Wireless Personal Area Networks (WPANs) interconnect devices within a relatively small area, generally within a persons reach. For example, both Bluetooth radio and invisible Infrared light provides a WPAN for interconnecting a headset to a laptop.Wi-Fi PANs are becoming commonplace (2010) as equipment designers start to integrate Wi-Fi into a variety of consumer electronic devices. Intel "My WiFi" and Windows 7 "virtual Wi-Fi" capabilities have made Wi-Fi PANs simpler and easier to set up and configure.

Wireless LAN

A wireless local area network (WLAN) links two or more devices using a wireless distribution method, providing a connection through an access point to the wider internet. The use of spread-spectrum or OFDM technologies also gives users the mobility to move around within a local coverage area, and still remain connected to the network.

Wi-Fi: "Wi-Fi" is a term used to describe 802.11 WLANs, although it is technically a declared standard of interoperability between 802.11 devices.

Fixed Wireless Data: This implements point to point links between computers or networks at two distant locations, often using dedicated microwave or modulated laser light beams over line of sight paths. It is often used in cities to connect networks in two or more buildings without installing a wired link.

Wireless MAN

Wireless Metropolitan Area Networks are a type of wireless network that connects several Wireless LANs.

WiMAX is a type of Wireless MAN and is described by the IEEE 802.16 standard.

Wireless WAN

Wireless wide area networks are wireless networks that typically cover large outdoor areas. These networks can be used to connect branch offices of business or as a public internet access system. They are usually deployed on the 2.4 GHz band. A typical system contains base station gateways, access points and wireless bridging relays. Other configurations are mesh systems where each access point acts as a relay also. When combined with renewable energy systems such as photo-voltaic solar panels or wind systems they can be stand alone systems.


Mobile devices networks


Global System for Mobile Communications (GSM): The GSM network is divided into three major systems: the switching system, the base station system, and the operation and support system. The cell phone connects to the base system station which then connects to the operation and support station; it then connects to the switching station where the call is transferred to where it needs to go. GSM is the most common standard and is used for a majority of cell phones.

Personal Communications Service (PCS): PCS is a radio band that can be used by mobile phones in North America and South Asia. Sprint happened to be the first service to set up a PCS.

D-AMPS: Digital Advanced Mobile Phone Service, an upgraded version of AMPS, is being phased out due to advancement in technology. The newer GSM networks are replacing the older system.


Uses:

Wireless networks continue to develop, usage has grown in 2010. Cellular phones are part of everyday wireless networks, allowing easy personal communications. Inter-continental network systems use radio satellites to communicate across the world. Emergency services such as the police utilize wireless networks to communicate effectively. Individuals and businesses use wireless networks to send and share data rapidly, whether it be in a small office building or across the world.

Another use for wireless networks is a cost effective means to connect to the Internet, in regions where the telecommunications infrastructure is both poor and lacking in resources, typically in rural areas and developing countries.

Compatibility issues also arise when dealing with wireless networks. Different devices may have compatibility issues, or might require modifications to solve these issues. Wireless networks are often typically slower than those found in modern versions of Ethernet cable connected installations.

A wireless network is more vulnerable, because anyone can intercept and sometimes divert a network broadcasting signal when point to point connections are used. Many wireless networks use WEP - Wired Equivalent Privacy - security systems. These have been found to be still vulnerable to intrusion. Though WEP does block some intruders, the security problems have caused some businesses to continue using wired networks until a more suitable security system can be introduced. The use of suitable firewalls overcome some security problems in wireless networks that are vulnerable to attempted unauthorized access.


Wireless Access Point vs. Ad Hoc Network

Some people confuse Wireless Access Points with Wireless Ad Hoc networks. An Ad Hoc network uses a connection between two or more devices without using a wireless access point: the devices communicate directly when in range. An Ad Hoc network is used in situations such as a quick data exchange or a multiplayer LAN game because setup is easy and does not require an access point. Due to its peer-to-peer layout, Ad Hoc connections are similar to Bluetooth ones and are generally not recommended for a permanent installation.

Internet access via Ad Hoc networks, using features like Windows' Internet Connection Sharing, may work well with a small number of devices that are close to each other, but Ad Hoc networks don't scale well. Internet traffic will converge to the nodes with direct internet connection, potentially congesting these nodes. For internet-enabled nodes, Access Points have a clear advantage, with the possibility of having multiple access points connected by a wired LAN.


Limitations of Wireless Access Point

One IEEE 802.11 WAP can typically communicate with 30 client systems located within a radius of 100 m.[citation needed] However, the actual range of communication can vary significantly, depending on such variables as indoor or outdoor placement, height above ground, nearby obstructions, other electronic devices that might actively interfere with the signal by broadcasting on the same frequency, type of antenna, the current weather, operating radio frequency, and the power output of devices. Network designers can extend the range of WAPs through the use of repeaters and reflectors, which can bounce or amplify radio signals that ordinarily would go un-received. In experimental conditions, wireless networking has operated over distances of several hundred kilometers.

Most jurisdictions have only a limited number of frequencies legally available for use by wireless networks. Usually, adjacent WAPs will use different frequencies (Channels) to communicate with their clients in order to avoid interference between the two nearby systems. Wireless devices can "listen" for data traffic on other frequencies, and can rapidly switch from one frequency to another to achieve better reception. However, the limited number of frequencies becomes problematic in crowded downtown areas with tall buildings using multiple WAPs. In such an environment, signal overlap becomes an issue causing interference, which results in signal droppage and data errors.

Wireless networking lags behind wired networking in terms of increasing bandwidth and throughput. While (as of 2010) typical wireless devices for the consumer market can reach speeds of 300 Mbit/s (megabits per second) (IEEE 802.11n) or 54 Mbit/s (IEEE 802.11g), wired hardware of similar cost reaches 1000 Mbit/s (Gigabit Ethernet). One impediment to increasing the speed of wireless communications comes from Wi-Fi's use of a shared communications medium, so a WAP is only able to use somewhat less than half the actual over-the-air rate for data throughput. Thus a typical 54 MBit/s wireless connection actually carries TCP/IP data at 20 to 25 Mbit/s. Users of legacy wired networks expect faster speeds, and people using wireless connections keenly want to see the wireless networks catch up.

By 2008 draft 802.11n based access points and client devices have already taken a fair share of the market place but with inherent problems integrating products from different vendors.

  • Digg
  • Del.icio.us
  • StumbleUpon
  • Reddit
  • RSS

Code For Designing a Pulse Counter

PULSE COUNTER :
This software is written in "C" language. In this software, first enable the timer and serial interrups. Then configure the timer by mode & reload the value to give the correct speed (9600 Baud). SCON gives necessary UART signal and your data is sent serially. When port pin P3.5 goes low, the internal counter increases by 1. This count is displayed on LCD as well as hyper terminal on PC.






PROGRAM:



#include

#define LCD P1

unsigned int Count,d1,d2,d3,d4,x1,x2,x3,x4;

sbit Pulse = P3^5;
sbit LED = P3^7;
sbit rs = P3^4;
sbit rw = P3^3;
sbit en = P3^2;

void LCDInit ( );
void lcdcmd (unsigned char );
void lcdwrt (unsigned char );
void Delay (unsigned int );
void Convert (unsigned int );
void SerialTx (unsigned char );

void main(void)
{
unsigned char z,Display;
unsigned char code str1[]=" PULSE COUNTER ";
unsigned char code str2[]=" Design By ";
unsigned char code str3[]=" SAMIK ";
unsigned char code str4[]=" SANTRA ";
unsigned char code str5[]="PULSE: 0000 ";
P0=0xFF;
P1=0xFF;
P2=0xFF;
P3=0xFF;
IE=0x00;

Count=0x00;

//////////////////////SERIALIZATION DATA//////////////
TMOD = 0x20;
TH1 = 0xFD;
SCON = 0x50;
TR1 = 1;

LED = 0x00;

LCDInit();

for(z=0;z<16;z++)
{

Display=str1[z];
lcdwrt(Display);
Delay(1);
SerialTx(Display);
Delay(1);
}

SerialTx('\r');
SerialTx('\n');
lcdcmd(0xC0);

for(z=0;z<16;z++)
{

Display=str2[z];
lcdwrt(Display);
Delay(1);
SerialTx(Display);
Delay(1);
}
Delay(200);

SerialTx('\r');
SerialTx('\n');
lcdcmd(0x01);
Delay(1);

for(z=0;z<16;z++)
{

Display=str3[z];
lcdwrt(Display);
Delay(1);
SerialTx(Display);
Delay(1);
}

SerialTx('\r');
SerialTx('\n');
lcdcmd(0xC0);

for(z=0;z<16;z++)
{

Display=str4[z];
lcdwrt(Display);
Delay(1);
SerialTx(Display);
Delay(1);
}
Delay(200);

SerialTx('\r');
SerialTx('\n');
lcdcmd(0x01);
Delay(1);

lcdcmd(0xC0);

for(z=0;z<16;z++)
{

Display=str5[z];
lcdwrt(Display);
Delay(1);
SerialTx(Display);
Delay(1);
}
Delay(70);

SerialTx('\r');
SerialTx('\n');

while(1)
{
LED=1;
Delay(30);
if(Pulse==0)
{
Count=Count+1;
Convert(Count);
if(Count==9999)
Count=0x00;
}
}
}

void Convert(unsigned int value)
{
x1 = value / 10;
d1 = value % 10;

x2 = x1 / 10;
d2 = x1 % 10;

x3 = x2 / 10;
d3 = x2 % 10;

d4 = x3 % 10;

d1=d1|0x30;
d2=d2|0x30;
d3=d3|0x30;
d4=d4|0x30;

lcdcmd(0xC7);

lcdwrt(d4);
lcdwrt(d3);
lcdwrt(d2);
lcdwrt(d1);
Delay(1);

SerialTx(d4);
SerialTx(d3);
SerialTx(d2);
SerialTx(d1);
Delay(1);

SerialTx('\r');
SerialTx('\n');

LED=0;
Delay(30);
}

void LCDInit()
{
lcdcmd(0x38);
Delay(10);
lcdcmd(0x0E);
Delay(10);
lcdcmd(0x01);
Delay(10);
lcdcmd(0x0C);
Delay(10);
lcdcmd(0x80);
Delay(10);
return;
}

void lcdcmd(unsigned char value)
{
LCD=value;
rs=0;
rw=0;
en=1;
Delay(1);
en=0;
return;
}

void lcdwrt(unsigned char value)
{
LCD=value;
rs=1;
rw=0;
en=1;
Delay(1);
en=0;
return;
}

void SerialTx(unsigned char value)
{
SBUF = value;
while(TI==0);
TI = 0;
}

void Delay(unsigned int x)
{
unsigned int i,j;
for (i=0;i<=x;i++)
for (j=0;j<=500;j++);
}

  • Digg
  • Del.icio.us
  • StumbleUpon
  • Reddit
  • RSS

Definition of EOF and how to use it effectively

The use and meaning of EOF seems to cause a lot of confusion with some new coders, hopefully this explanation will help you

understand better. Before I go into too much detail about what EOF is, I'll tell you what it isn't.

EOF is NOT:

# A char

# A value that exists at the end of a file

# A value that could exist in the middle of a file

And now to what it actually is.

EOF is a macro defined as an int with a negative value. It is normally returned by functions that perform read operations to denote

either an error or end of input. Due to variable promotion rules (discussed in detail later), it is important to ensure you use an int to

store the return code from these functions, even if the function appears to be returning a char, such as getchar() or fgetc().

Here are some code examples that you might use:

int c;

while ((c = fgetc(fp)) != EOF)
{
putchar (c);
}



int ch;

while ((ch = cin.get()) != EOF)
{
cout <<(char)ch;
}



char to int Promotion

By definition an int is larger than a char, therefore a negative valued int can never hold the same value as a char. However, when you

compare an int with a char, the char will get promoted to an int to account for the difference in size of the variables. The value of a

promoted char is affected by its sign, and unfortunately, a char can be either signed or unsigned by default, this is compiler

dependant.

To understand this better, let's look at the representation of a few numbers in both ints and chars.

The following assumes 2 byte ints (your compiler might use a larger amount). A char uses only 1 byte (this will be the same amount

on your compiler). With the exception of the first column, the values are shown in hexadecimal.

------------------------------------------ --------------------------------------
| char and int comparison | | char to int promotion |
------------------------------------------- --------------------------------------
| Decimal | int | char | | char | unsigned | signed |
|---------------|-------------|---------| |---------|-----------------|-------------|
| 2 | 00 02 | 02 | | 02 | 00 02 | 00 02 |
| 1 | 00 01 | 01 | | 01 | 00 01 | 00 01 |
| 0 | 00 00 | 00 | | 00 | 00 00 | 00 00 |
| -1 | FF FF | FF | | FF | 00 FF | FF FF |
| -2 | FF FE | FE | | FE | 00 FE | FF FE |
----------------------------------------- -------------------------------------------


The "char to int promotion" table makes it clear that the sign of a char produces a very different number in the int.

So what does all this mean to me as a programmer?

Well, let's have a look at a revised version of the code shown above, this time incorrectly using a char variable to store the return

code from fgetc().

char c;

while ((c = fgetc(fp)) != EOF)
{
putchar (c);
}



Now let's assume that within the file we are reading from is a byte with value 0xff. fgetc() returns this value within an int, so it looks like

this: 0x00 0xff (again, I'm assuming 2 byte ints). To store this value in a char, it must be demoted, and the char value becomes 0xff.

Next, the char c is compared with the int EOF. Promotion rules apply, and c must be promoted to an int. However, in the sample code,

the sign of c isn't explicitly declared, so we don't know if it's signed or unsigned, so the int value could become either 0xff 0xff or 0x00

0xff. Therefore, the code is is not guaranteed to work in the way we require.

The following is a short program to help show the promotion:

#include

int main(void)
{
int i = -1;
signed char sc = 0xff;
unsigned char usc = 0xff;

printf ("Comparing %x with %x\n", i, sc);
if (i == sc) puts("i == sc");
else puts("i != sc");
putchar ('\n');
printf ("Comparing %x with %x\n", i, usc);
if (i == usc) puts("i == usc");
else puts("i != usc");

return 0;
}

/*
* Output

Comparing ffff with ffff <--- Notice this has been promoted
i == sc

Comparing ffff with ff
i != usc

*
*/

Another scenario to consider is where the char is unsigned. In this case, the process of demoting and promoting the returned value

from fgetc() will have the affect of corrupting the EOF value, and the program will get stuck in a infinite loop. Let's follow that process

through:

- EOF (0xff 0xff) is returned by fgetc() due to end of input
- Value demoted to 0xff to be stored in unsigned char c
- unsigned char c promoted to an int, value goes from 0xff to 0x00 0xff
- EOF is compared with c, meaning comparison is between 0xff 0xff and 0x00 0xff.
- The result is FALSE (the values are different), which is undesirable.
- fgetc() is called again, and still returns EOF. The endless loop begins.



The following code demonstrates this problem.

#include

int main(void)
{
FILE *fp;
unsigned char c;

if ((fp = fopen("myfile.txt", "rb")) == NULL)
{
perror ("myfile.txt");
return 0;
}

while ((c = fgetc(fp)) != EOF)
{
putchar (c);
}

fclose(fp);
return 0;
}







Why it's bad to use feof() to control a loop ???




When reading in a file, and processing it line by line, it's logical to think of the code loop as "while not at the end of the file, read and

process data". This often ends up looking something like this:

i = 0;

while (!feof(fp))
{
fgets(buf, sizeof(buf), fp);
printf ("Line %4d: %s", i, buf);
i++;
}



This apparently simple snippet of code has a bug in it, though. The problem stems from the method feof() uses to determine if EOF

has actually been reached. Let's have a look at the C standard:

The feof function

Synopsis

1 #include
int feof(FILE *stream);

Description
2 The feof function tests the end-of-file indicator for the stream pointed to by stream.

Returns
3 The feof function returns nonzero if and only if the end-of-file indicator is set for stream.



Do you see the problem yet? The function tests the end-of-file indicator, not the stream itself. This means that another function is

actually responsible for setting the indicator to denote EOF has been reached. This would normally be done by the function that

performed the read that hit EOF. We can then follow the problem to that function, and we find that most read functions will set EOF

once they've read all the data, and then performed a final read resulting in no data, only EOF.

With this in mind, how does it manifest itself into a bug in our snippet of code? Simple... as the program goes through the loop to get

the last line of data, fgets() works normally, without setting EOF, and we print out the data. The loop returns to the top, and the call to

feof() returns FALSE, and we start to go through the loop again. This time, the fgets() sees and sets EOF, but thanks to our poor logic,

we go on to process the buffer anyway, without realising that its content is now undefined (most likely untouched from the last loop).

This problem results in the last line being printed twice. Now, with the various code and compilers I've tried, I've seen varying results

when using this poor quality code. Some give the wrong answer as described here, but some do seem to get it right, and print the last

line only once.

Here is a full example of the broken code. It's pointless providing sample results, as they're not necessarily going to be the same as

yours. However, if you compile this code, and run it against an empty file (0 bytes), it should output nothing. If it's doing it wrong, as I

expect it will, you'll get a line similar to this:

Line 0: Garbage

Here, Garbage was left in the buffer from the initialisation, but should not have been printed. Anyway, enough talk, here's the code.

#include
#include

#define MYFILE "junk1.txt"

int main(void)
{
FILE *fp;
char buf[BUFSIZ] = "Garbage";
int i;

if ((fp = fopen(MYFILE, "r")) == NULL)
{
perror (MYFILE);
return (EXIT_FAILURE);
}

i = 0;

while (!feof(fp))
{
fgets(buf, sizeof(buf), fp);
printf ("Line %4d: %s", i, buf);
i++;
}

fclose(fp);

return(0);
}



To correct the problem, always follow this rule: use the return code from the read function to determine when you've hit EOF. Here is a

revised edition of the same code, this time checking the return code from fgets() to determine when the read fails. The code is exactly

the same, except for the loop.

#include
#include

#define MYFILE "junk1.txt"

int main(void)
{
FILE *fp;
char buf[BUFSIZ] = "Garbage";
int i;

if ((fp = fopen(MYFILE, "r")) == NULL)
{
perror (MYFILE);
return (EXIT_FAILURE);
}

i = 0;

while (fgets(buf, sizeof(buf), fp) != NULL)
{
printf ("Line %4d: %s", i, buf);
i++;
}

fclose(fp);

return(0);
}



When this is run against an empty file (0 bytes), it will not print anything.

Here are some other read functions being used to control loops:

total = 0;

while (fscanf(fp, "%d", &num) == 1)
{
total += num;
}

printf ("Total is %d\n", total);



int c;

while ((c = fgetc(fp)) != EOF)
{
putchar (c);
}



  • Digg
  • Del.icio.us
  • StumbleUpon
  • Reddit
  • RSS

After Infosys & Wipro, I-T department initiates scrutiny on TCS:

After Infosys & Wipro, I-T department initiates scrutiny on TCS:


I-Tax Dept has initiated scrutiny on TCS for claiming tax benefits for onshore services. Onshore software services account for close to 45% of cos' $8-bn revenues.
In a scrutiny notice initiated a few days ago, the I-T Department has revisited its argument that onshore software services provided by Indian exporters boil down to export of manpower, rather than software, a senior tax official said.

Onshore development refers to the practice of IT companies sending their staff to work in overseas markets, including the US and Europe. Often, such services are rendered in the premises of the overseas client. The Income-Tax Department has argued that since professionals are under the control and supervision of the company abroad, the contract between the local software company and the foreign client amounts to export of manpower.


Simultaneously, tax authorities say many software companies often book the earnings from such onshore work in their units located in the Software Technology Parks of India (STPI) to avail tax benefits.

Responding to an email, a TCS spokesperson said: "As a policy we do not comment on tax-related issues." According to a senior tax practitioner, the timing of the notice is important. "While there is no longer tax holiday for STPIs and EOUs (except for units in SEZs) from April 1, 2011, the government continues to be under pressure to generate revenues," said Indraneel Roy Chaudhury, Tax Leader, South India Practice, PwC.

Interestingly, under Indian tax rules, "human resource services" can get the benefit of tax holiday. "But on this," he said, "one needs to examine contracts to determine what would fall within this purview."


MUMBAI: It's now the turn of India's largest software company to spell out its stand on a tricky point that tax authorities have been raking up.

After Infosys and Wipro, the Income-Tax Department has initiated scrutiny on Tata Consultancy Services (TCS) for claiming tax benefits for onshore services, often derogatorily called 'body shopping'. Onshore software services account for close to 45% of TCS' $8-billion revenues.

In a scrutiny notice initiated a few days ago, the I-T Department has revisited its argument that onshore software services provided by Indian exporters boil down to export of manpower, rather than software, a senior tax official said.

Onshore development refers to the practice of IT companies sending their staff to work in overseas markets, including the US and Europe. Often, such services are rendered in the premises of the overseas client. The Income-Tax Department has argued that since professionals are under the control and supervision of the company abroad, the contract between the local software company and the foreign client amounts to export of manpower.


Simultaneously, tax authorities say many software companies often book the earnings from such onshore work in their units located in the Software Technology Parks of India (STPI) to avail tax benefits.

Responding to an email, a TCS spokesperson said: "As a policy we do not comment on tax-related issues." According to a senior tax practitioner, the timing of the notice is important. "While there is no longer tax holiday for STPIs and EOUs (except for units in SEZs) from April 1, 2011, the government continues to be under pressure to generate revenues," said Indraneel Roy Chaudhury, Tax Leader, South India Practice, PwC.

Interestingly, under Indian tax rules, "human resource services" can get the benefit of tax holiday. "But on this," he said, "one needs to examine contracts to determine what would fall within this purview."

  • Digg
  • Del.icio.us
  • StumbleUpon
  • Reddit
  • RSS