c programming by example

Upload: martin-whitbread

Post on 09-Apr-2018

223 views

Category:

Documents


0 download

TRANSCRIPT

  • 8/8/2019 C Programming by Example

    1/33

    Computer Based Applications

    "How Software Works"

    Author ~ Martin Whitbread

  • 8/8/2019 C Programming by Example

    2/33

    This document is in two parts. The first is in sections and contains a series of

    exercises that should be worked on using the DevCpp Integrated Development

    Environment. These should be documented and shown on request, to your

    supervisor. The second part applies many of the skills acquired in the first part todevelop a game program that emulates a Pin Ball table.

    The marks applied are: Part 1 - 40%

    Part 2 - 60%

    Your work should NOT just be a collection of code listings but should be a

    discourse where the code illustrates points. Results need to be recorded and the

    results of any more interesting tests that are applied. Do NOT copy work, all

    parties will be penalized if this is detected, work individually and meet deadlines.

    MJW

  • 8/8/2019 C Programming by Example

    3/33

    IntroductionIn today's world software is everywhere, often hidden from the user as an integral part of of the

    system. So when a button on a remote control is pressed, or a key on a mobile phone, layers of

    electronics and controlling software are activated. Programming these systems is not easy, they

    have to function reliably and accurately for the live of the system. There may be health and safety

    issues, with lives or property at risk if the design is not robust or the software faulty. Applications ofsoftware extend far beyond the simple PC or laptop and are much more demanding on the

    designers, implementers and testers. There is no reset button on a pacemaker or a jumbo jet.

    http://boeing.com/commercial

    Software tools have evolved considerably over the last 40 years or so. A lot of code is

    still written in a programming language, to be compiled and tested in a suitable

    environment. Early languages were low level - they matched the architecture of the

    processor and were specific for that machine. Later came languages such as Fortran

    (Formula Translation) and COBOL (Common Business Oriented Language) which

    advanced the number of scientific and business applications that could be written for

    the large mainframe computers then in use. Other languages followed, including the

    widely used language 'C'. While C is a relatively low level language, in includes

    many high level constructs. The ability of C to process data at bit level meant that it

    has been able to replace most of the machine specific assembly (low) level languages

    used on embedded systems projects. The later extension of the C syntax to include

    object oriented design concepts as C++ has meant that large software projects can be

    built around libraries of proven objects. Other languages have been developed from

    C++ , including Java and C#. The basic syntax of C stays more or less the same inthese languages. An understanding of C leads to a much better appreciation of the

    logic in applications written in these languages. Progressing from C to C++ becomes

    relatively easy, once an understanding of object oriented programming is achieved.

    These languages evolve over the years and with the increasing use of multi-core

    processors new versions or even new languages are bound to appear, sooner rather

    than later.

    An example - C program

    A program has a carefully defined structure. It needs a start and end point and also

    must itemize any special features such as libraries that may be needed. C programs

    need to be written according to certain rules (syntax). These rules need to be followed

    otherwise the program will probably fail to compile, or if it does compile, it may do

    the wrong thing. A very basic program looks like :

    http://boeing.com/commercialhttp://boeing.com/commercial
  • 8/8/2019 C Programming by Example

    4/33

    Example 1.1

    #include #include

    int main()

    {printf("This is an example of a C program ");getch();return 0;

    }

    The line #include identifies the "header" file stdio.h which ensures that the

    standard I/O library is included in the program, providing standard C input/output

    facilities. The conio.h header allows various console I/O functions to be used. These

    include the key read function 'getch()' - in this program it is there to stop the programso you can read the output, otherwise it would just flash by too quickly. This program

    starts at 'main() { ' and ends at the last '}' .

    So we have seen that a program runs sequentially, beginning at main() and finishing

    at the last brace (}). This is not the end of the story by any means, software is useful

    because it can make decisions and it can loop. A program can test inputs and act

    accordingly, if the input is wrong then remedial action can be take. Such actions are

    difficult to implement in pure hardware and any such solution is likely to lack

    flexibility. Consider :

    Example 1.2

    #include #include int main()

    {char ch;

    printf("Enter a number from 1 to 4 \n");

    ch = getch();if(ch< '1' || ch > '4') // is it < '1' OR > '4'?{

    printf("You pressed the wrong key \n");}else{

    printf("You pressed %c ",ch);}

    getch();return 0;

    }

  • 8/8/2019 C Programming by Example

    5/33

    This program reads a key in using getchar() and then tests the value to see if it is less

    than 1 or greater 4, in terms of the 8-bit ASCII value read from the keyboard. Note -

    the logical OR operation is denoted by || in C. The %c entry in a printf() refers to

    the character variable 'ch' declared in the program. So, the input is wrong if it is less

    than '1' or greater than '4', otherwise it is correct and printed out.

    Now try:-

    Example 1.3

    #include #include

    int main(){

    char ch;printf("Enter a number from 1 to 4 \n");ch = getch();while (ch< '1' || ch > '4'){

    printf("You pressed the wrong key \n");ch = getch();

    }printf("You pressed %c ",ch);

    getch();return 0;}

    Software can loop, using a while statement the program is now locked in a loop until

    a correct entry is made. Note that the key is read before the loop (once) and then in

    the loop, after the test, so that it tests the new key each time. Without that it would

    test the original key which would be incorrect.

    We can break out of the program using:-

    if(ch=='q')

    Exercise 1.1

    Try changing the test range so that another number range is accepted. The try a

    character range, say 0 to z. What can you tell from this about the ASCII character

    set? Look at the full table on http://www.asciitable.com/.

  • 8/8/2019 C Programming by Example

    6/33

    {return 0;}

    We can now look a bit further at the keyboard itself and see what information it

    provides for a computer system to respond to. If you look at the ASCII code table

    mentioned earlier you will see that not all the keys on your keyboard are present. The

    keyboard logic plays a clever trick and sends two characters for those keys, the first is

    an 'escape' code (sometimes a zero byte) followed by a familiar character. This pair

    represents the key e.g. is represented by 00 3b in hexadecimal (null, ; ).

    Example 1.4

    #include #include int main()

    {char ch;

    printf("Enter any key \n");ch = getch();while (ch != 'q')

    {printf("You pressed the %c key - %x in hex \n",ch,ch);ch = getch();

    }printf("Goodbye - hit any key to close");getch();return 0;

    }

    In printf() we can show the hexadecimal value of a variable with %x, note that the %

    entries in the text line are matched by a list of the appropriate variables after the text

    quotes have closed. Text is always shown in double quotes - "this is a text string", and

    Exercise 1.2

    Try putting this into the program to see if the program can be made to quit on 'q'.

    Exercise 1.3

    Run the program below and examine the values of keys. You should become

    familiar with values for , 0-9 and the start of the upper and lower case

    alphabet. You should try combinations such as c, and compare the

    results with the ASCII table.

  • 8/8/2019 C Programming by Example

    7/33

    a single character is shown in single quotes - 'q', The difference? A text string has an

    extra byte on the end (null) to indicate that the end has been reached - corrupt that

    and you are in trouble!

    Hint: Consider using an exclusive OR operation, enter a key variable at the start

    and then Exclusive OR the character with the key using ch^key. It works sometimes.

    (Bit-wise operations in C are & = AND, | = OR, ^ = Exclusive OR and ~ = invert. Do

    not confuse these with LOGICAL operations using && and || as in while (ch< '1' ||ch > '4')).

    Exercise 1.4

    i) Write a program that writes each character to the screen as typed until is

    pressed. Remember = 00 3b, so just look for the null (00).

    ii) Modify this program so that the text is printed in an encoded format. Can you

    think of a way to do this so that the text can be reentered to recover what was

    pressed. Like an Enigma machine!

  • 8/8/2019 C Programming by Example

    8/33

    SECTION 2 - Program Structure

    It is possible to write computer software that works but is both unreadable and

    virtually impossible to modify. Software needs to have a structure so that it can easilybe understood by others and has a form of logic that means that it will meet any

    situation that arises, not just the input that was planned but any input that might

    occur. Quite a few software applications can be implemented as state machines. That

    is, they move through a series of states as the application progresses. This often

    applies to parts of an application as well, such as opening up a communication link.

    If we consider an ATM application where the machine waits for a card, then for a PIN

    number followed by a service selection, then we can divide it up into states:-

    State Activity Input

    0 Wait for card c and 0000-9999(PIN)

    1 Enter service request A,W or R

    2 Show balance

    3 Request cash

    4 Print statement

    9 Eject Card

    The 9th state leaves room for others to be added, this can be implemented using the

    'switch' statement C where the variable controlling the flow of the logic is used to

    select the appropriate 'case'. This is a common technique in engineering applicationsin a wide range of languages. Note that the state variable "state" is initialized to zero

    so that we start with requesting a debit card.

    Example 2.1

    #include

    #include #include

    int state=0;

    /*State variable*/char in;

    int main()

    {

    while(1){

    /*Tells you what state it is inprintf("State = %d\n",state);*/

    switch(state)

    {

  • 8/8/2019 C Programming by Example

    9/33

    case 0:printf("Enter card - \n"); /* enter 'c' to represent the card input */

    in=getch();

    if (in== 'c')

    {

    printf("Enter PIN\n");getch();putch('*');

    getch();

    putch('*');getch();

    putch('*');getch();

    putch('*');

    printf("PIN OK\n\n\n");state = 1;

    /*These follow so they are only printed once, the state now changes*/printf("Select option\n");

    printf("Account Balance - \n");

    printf("Withdraw Cash - \n");printf("Request Printed Statement - \n");

    }break;

    case 1:

    /*select user interface option*/in=getch();

    if(in=='A'){ state = 2;}

    if(in=='W')

    { state = 3;}if(in=='R')

    { state = 4;}break;

    case 2:printf("Your account balance = %d.42\n",rand()/100); /*pseudo random amount*/

    /* getchar();*/

    state=9;break;

    case 3:

    printf("Please enter an amount - in ten pound steps\n"); /*no more steps here*/getchar();

    state=9;

    break;

    case 4:printf("Please take your statement\n"); /*no more steps here*/

    getchar();state=9;break;

  • 8/8/2019 C Programming by Example

    10/33

  • 8/8/2019 C Programming by Example

    11/33

    Now, if you have a program that compiles, and runs, think about the way it operates.

    the PIN feature is meant to give 10,000 options for getting the number right and the

    system detects multiple trys, eventually retaining the card. However, our model has a

    logical flaw, you can derive the PIN after 10+10+10+10 trys instead of 10x10x10x10.

    That is because it ejects after a single incorrect digit has been pressed. The sequence

    to extract this PIN would be:

    0 -> (eject card)

    1 * (correct 1st digit)0 -> (eject)

    1 -> (eject)

    2 * (correct 2nd digit)

    0 ->

    1 ->

    2 ->

    3 * (correct 3rd digit)

    0 ->

    1 ->

    2 ->

    3 ->

    4 * (correct 4th digit)

    So after 14 attempts, the PIN is revealed. To correct this feature the PIN must be

    loaded completely before checking, putting the digits into an empty array:

    char buf[4]; /*Empty character array */

    We can use this array as:

    for(loopcount=0;loopcount

  • 8/8/2019 C Programming by Example

    12/33

    Debugging your program

    Once you have a program that will compile, key to open the debug window.

    Move the cursor to a line at the start of the program and use Ctrl F4 (run to cursor)

    Now you can step the program - and/or set a watch on a variable e.g.

    'loopcount'.

    As you step over a getch() you must click on the DOS window prompt so that the

    character can be entered (only in this window).

    Experiment with break points, run the code normally after clicking on a line in the

    code so that it shows highlighted in red.

    Conclusions : The code might compile and run but it might not be logically correct.

    Always examine the specification carefully and identify any likely problems. These

    can be corrected by adding additional features, if it all works, no one will commenton the change, they will not want any specification error being pointed out!

    Exercise 2.2

    Can you put these routines into your code and verify that it works as predicted.

  • 8/8/2019 C Programming by Example

    13/33

    SECTION 3 - Graphics

    In order for a program to be compiled with various libraries and other code that may

    be needed, the user needs to provide a lot of information. This can be quite tiresometo key in every time and it is easy to make mistakes. One early option was to record

    the complex command line in text file and provide that as part of a "batch file". This

    technique is still used in some operating environments. If you have a development

    environment like Dev Cpp then you can create a project file and set up the right

    parameters in that. Then it is quite simple case of compiling as before. To use a

    simple form of graphics with Dev Cpp, it is necessary to bring in the Borland

    Graphical Interface library that has been ported to this environment and is supported

    by the guys at the University of Colorado, on-line documentation is to be found at:

    http://www.cs.colorado.edu/~main/bgi/doc/

    Example 3.1

    #include #include

    #include

    int main()

    {float offset;

    int i,x1,y1;initwindow(600,600);setfillstyle(1,YELLOW);

    fillellipse(300,300,30,30);getchar();

    }

  • 8/8/2019 C Programming by Example

    14/33

  • 8/8/2019 C Programming by Example

    15/33

    Example 3.3

    #include

    #include

    int main()

    {int i,x1,y1;

    x1 = 300;

    y1 = 300;initwindow(600,600);

    setfillstyle(1,YELLOW);setcolor(BLACK); /*SET RIM OF CIRCLE TO BLACK */

    for(i=0;i

  • 8/8/2019 C Programming by Example

    16/33

    Exercise 3.2

    If we want to bounce the disc off of the edge, we need to reverse the increment

    of x, so that it moves back to the left. If we replace thefor (i=0;i

  • 8/8/2019 C Programming by Example

    17/33

    SECTION 4 - Using Maths functions

    Example 4.1#include

    #include #include

    int main()

    {float offset;

    int i,x1,y1;initwindow(900,900);

    setcolor(BLACK);

    while(1){

    setfillstyle(1,YELLOW);//calculate moon position x1 has bigger offset so orbit is elipse

    x1=(sin(offset)*200)+400;

    y1=(cos(offset)*100)+400;//draw moon

    fillellipse(x1,y1,15,15);

    //draw planet

    setfillstyle(1,RED);fillellipse (400,400,60,65);

    //blank moon after delayfor(i=0;i

  • 8/8/2019 C Programming by Example

    18/33

    Note on collisions:

    We can use Pythagoras' theorem to find the distance between two objects.

    [x1,y1]

    Distance y1-y2

    x1-x2

    [x2,y2]

    2 2 2Distance = (x1-x2) + (y1-y2)

    if((int)sqrt((double)((x1-x2)*(x1-x2))+ ((y1-y2)*(y1-y2)))

  • 8/8/2019 C Programming by Example

    19/33

    SECTION 5 - Functions, Structures and Objects

    Functions

    We have already used predefined functions like printf(). It is obvious they are a useful

    way of carrying out operations that would otherwise have to be implemented with

    blocks of code that would reoccur throughout the program. We can create our own

    functions in one of two different ways. If we define our function after the main()

    block, then a 'prototype' of the function (consisting of its header line terminated with

    a semicolon (;), is needed before main. Otherwise, defining a function before main()

    means that no prototype is needed:

    Example 5.1#include void tick(); /*prototype for function tick */

    void tock() /*function defined ahead of main, no need for prototype*/

    {printf("TOCK\n");

    }int main()

    {

    while(1)

    {tick(); /*function calls */tock();

    }

    }void tick() /*definition of function tick */

    {printf("TICK\n");

    }

    We can send various data items to a function including pointers to data but a function

    only returns a single item as in:

    ch= getch();

    (You can tell its a function by the brackets.) ch=key; is not a function call!

  • 8/8/2019 C Programming by Example

    20/33

    Structures

    It is very useful to be able to group related item of data in a structure. This might be a

    record to be written to a file or the information relating to some kind of item in the

    code. The structure below is a descriptor of a data set that a graphic object needs to

    operate. It will not exist as data until it is declared.

    struct BUTTON {int x;

    int y;

    int on_color;int off_color;

    int state;int buffer[2000];

    };

    struct LIGHT {int x;

    int y;

    int on_color;int off_color;

    int state;};

    The complete program looks like :-

    #include

    #include

    #define ON 1

    #define OFF 0

    struct BUTTON {int x;

    int y;

    int on_color;

    int off_color;int state;

    int buffer[2000];

    };

    struct LIGHT {

    int x;int y;

    int on_color;int off_color;

    int state;};

  • 8/8/2019 C Programming by Example

    21/33

    void initbutton(BUTTON *button_str,int xpos,int ypos,int on,int off){

    button_str->x=xpos;button_str->y=ypos;

    button_str->on_color=on;

    button_str->off_color=off;

    button_str->state=OFF;

    }

    void initlight(LIGHT *light_str,int xpos,int ypos,int on,int off){

    light_str->x=xpos;light_str->y=ypos;

    light_str->on_color=on;

    light_str->off_color=off;

    }void drawlight(LIGHT *light_str)

    {

    setfillstyle(1,LIGHTGRAY);fillellipse(light_str->x,light_str->y,12,13);

    if(light_str->state==ON){

    setfillstyle(1,light_str->on_color);

    }else

    {setfillstyle(1,light_str->off_color);

    }

    fillellipse(light_str->x,light_str->y,10,10);setfillstyle(1,LIGHTGRAY);

    bar(light_str->x-4,light_str->y-4,light_str->x+2,light_str->y-2);

    }

    void setlight(LIGHT *light_str,int state){

    if(state >=0)

    { light_str->state =state;

    drawlight(light_str);}

    }int drawbutton(BUTTON *button_str)

    {

    setfillstyle(1,LIGHTGRAY);bar(button_str->x-22,button_str->y-22,button_str->x+22,button_str->y+22);

    setfillstyle(1,WHITE);bar(button_str->x-26,button_str->y-26,button_str->x+26,button_str->y-23);

    bar(button_str->x-26,button_str->y-26,button_str->x-23,button_str->y+26);setfillstyle(1,DARKGRAY);bar(button_str->x-26,button_str->y+23,button_str->x+26,button_str->y+26);

  • 8/8/2019 C Programming by Example

    22/33

  • 8/8/2019 C Programming by Example

    23/33

    initbutton(&button3, 300,200,BLACK,YELLOW);

    initlight(&light1, 100,250,YELLOW,GREEN);initlight(&light2, 200,250,BLACK,RED);

    initlight(&light3, 300,250,WHITE,BLUE);

    drawbutton(&button1);drawbutton(&button2);drawbutton(&button3);

    drawlight(&light1);drawlight(&light2);

    drawlight(&light3);

    while(!kbhit())

    {s =getbutton(&button1);

    setlight(&light1,s);s =getbutton(&button2);

    setlight(&light2,s);

    s =getbutton(&button3);setlight(&light3,s);

    }closegraph();

    return 0;

    }

    Compile this program using a project file as before.

    This can be run to produce this result:

    This program runs in a continuous loop, left click on a button to see its operation.

  • 8/8/2019 C Programming by Example

    24/33

    The initialization routines simply load the structures with the given variables.

    void initbutton(BUTTON *button_str,int xpos,int ypos,int on,int off){

    button_str->x=xpos;button_str->y=ypos;

    button_str->on_color=on;

    button_str->off_color=off;button_str->state=OFF;

    }void initlight(LIGHT *light_str,int xpos,int ypos,int on,int off)

    {

    light_str->x=xpos;light_str->y=ypos;

    light_str->on_color=on;

    light_str->off_color=off;}

    void setlight(LIGHT *light_str,int state){

    if(state >=0)

    {light_str->state =state;

    drawlight(light_str);}

    }

    The calling routine sends the address of the structure descriptor to the initializerwhich is then used to point to the structure elements.

    This shows that the structures and the code routines are closely related and there is

    likely to be some private functions that these use that the user would not normally

    access.

    Once you have built the structure you will have to create an instance of it, as in:-

    BALL ball1; /*declaring a ball known as ball1*/

    Now you need a function to initialize the ball, giving the address of ball1 (&ball1) tothe function, as well as its initial position and its colour. See above.

    Exercise 5.1

    Go back to the "bouncing ball" program and edit it, creating a structure for the "ball"

    giving its position, colour, radius and direction.

  • 8/8/2019 C Programming by Example

    25/33

    File Handling

    Files are handled using a file pointer of type FILE. This creates a structure containing

    details of the file including a link to the file control block. A byte counter is increased

    with every access and can be reset using rewind(). Program below opens a file

    "test.txt" (in your current working directory) which holds :-

    jack

    100

    It amends the file with new data, in the same directory. For other pathsfopen uses \\as the first \ is an escape character as in \n. (newline)

    You can usefprintfandfscanfin the same way that printf and scanf are used

    except that the syntax would be as fprintf(out,"%s\n%s\n",name,score);

    where out is a file pointer.FILE *in creates a pointer to a type FILE. From then on'in'refers to the pointer, which will be set to NULL if the file does not exist.

    #include int main(void)

    {

    char newname[] = "john"; char newscore[] = "123";

    char oldname[40];char oldscore[4];

    FILE *in; /*File pointer */

    if ((in = fopen("test.txt", "r+"))== NULL){

    fprintf(stderr, "Cannot open input file.\n");

    Exercise 5.2

    Can you now modify the rest of the program to use the fields in the structure, so thatx1becomesball1.x1. This is a way accessing the field within a structure which

    declared locally. Make sure that it runs like the original. Keep this program safe, you

    will need need it later.

    Exercise 5.3

    This program can be altered to create a file using "w+" if it does not already exist, seeif you can do it.

  • 8/8/2019 C Programming by Example

    26/33

    getchar();return 0;

    }fscanf(in,"%s%s",oldname,oldscore);

    rewind(in);

    printf("Original file holds : %s %s",oldname,oldscore);

    fprintf(in,"%s\n%s\n",newname,newscore);rewind(in);fscanf(in,"%s%s",oldname,oldscore);

    rewind(in);

    printf("\nNew file holds : %s %s",oldname,oldscore);getchar();

    fclose(in);printf("\nOK \n");

    getchar();

    return 0;}

    else

    { if ((in = fopen("test.txt", "w+"))== NULL){

    fprintf(stderr, "Cannot open input file.\n");

    getchar();return 0;

    }

    From then, its business as before:

    fprintf(in,"%s\n%s\n",newname,newscore); /*write data to file*/

    Exercise 5.4

    How to change it:

    We need to reverse the logic on the line that opens the file, so that if it exists, it is

    read (fscanf) and the contents printed out (printf). to do this we need to change this

    line to:if ((in = fopen("test.txt", "r+"))!= NULL)notice the change?

    Now we can follow that with:

    { fscanf(in,"%s%s",oldname,oldscore);rewind(in);

    printf("Original file holds : %s %s",oldname,oldscore); }

    If thefopen returns a NULL it means that there is no such file and we have to create

    one using "w+". So, using an 'else' we can take the reverse logic and try and open a

    file of that name for writing:

  • 8/8/2019 C Programming by Example

    27/33

    rewind(in); /*go back to start*/fscanf(in,"%s%s",oldname,oldscore); /* Read (new) data */

    rewind(in);printf("\nNew file holds : %s %s",oldname,oldscore);

    C++ Objects

    This leads use to the basic concept of objects as used in C++, Java, C# and whatever

    else comes next. The program below is in C++. Try it out. Notice thatset_values isaccessed as rect.set_values, as a function once it has been declared, just like

    accessing the data in a C structure. In this case it is also set as public within the classCRectangle, making it accessible.

    Example 5.2// C++ classes example from http://www.cplusplus.com/doc/tutorial/classes/

    #include using namespace std;

    class CRectangle {int x, y;

    public:

    void set_values (int,int);int area () {return (x*y);}

    };

    void CRectangle::set_values (int a, int b) {

    x = a;y = b;

    }

    int main () {

    CRectangle rect;rect.set_values (3,4);

    cout

  • 8/8/2019 C Programming by Example

    28/33

    definition. For example, in the function set_values() of the previous code, we have been able

    to use the variables x and y, which are private members of class CRectangle, which means they

    are only accessible from other members of their class. "

    So you can see, C++ is not easy to learn from scratch, a good knowledge of C helps a

    great deal. Java is slightly less complex than C++. C# is tied to Microsoft and is notportable across other operating systems.

  • 8/8/2019 C Programming by Example

    29/33

    Section 6 - Multitasking

    It may come as a surprise but there are far more microprocessors in your life than the

    few obvious ones you see every day. You may think that Windows is the onlycomputer operating system around but every phone has a specialized operating

    system, others, called Real Time Operating Systems are to be found providing your

    power, water, food, transport and health care. These systems have to stay live day

    after day, year after year. There is no rebooting an atomic power station or an

    intensive care monitor, they just have to work. These systems share a common

    feature, they run code as a set of cooperating tasks that time share the central

    processor. This multi-tasking allows tasks with a higher priority to get a larger share

    of the CPU's time. They can also communicate and synchronize through a variety of

    mechanisms including the one we are going to see here, the pipeline.

    InP

    Pipe Buffer

    OutP Pointers wrapround to start

    A pipe can be used to link two tasks so that neither has to wait when data is

    transferred, unless it is full or empty.

    Multitasking

    In an RTOS there are multiple tasks running, with different priorities and fast

    response mechanisms are provided for interrupts and other events. The task

    scheduling is carried by a scheduler that is driven by a timer interrupt. Multitasking

    also takes place in non-real time operating systems such as Windows and Linux.

    A way of achieving multi-tasking without a scheduler is known as cooperative

    multitasking. This technique can be used to divide an application into tasks, where

    some tasks have lower priority and run less often. It can even be applied to simple

    microcontrollers such as the PIC 16F8x devices. Here an application is split intomajor functions, representing the tasks. These are run in a switch-case architecture

    and can be selected according to priority. The major difficulty is that tasks have to

  • 8/8/2019 C Programming by Example

    30/33

    hand control back to the scheduling routine, if they do not, the whole application

    comes to a halt. (Remember Windows 95!).

    /*A demonstration of Cooperative Multitasking

    each task is run in turn, a delay loop slows the system down sothat the user can interact. Priorities are applied based on the loop counter

    the lower the value the more likely count%(modulus)priority will produce a zero*/

    // This is needed for DevC++, comment out for MPLAB

    #include

    //Comment out for DevC++, leave in for MPLAB

    /*#if defined(__PCM__)

    #include #fuses HS,NOWDT,NOPROTECT

    #use delay(clock=20000000)

    #use rs232(baud=9600, xmit=PIN_C6, rcv=PIN_C7) // Jumpers: 8 to 11, 7 to 1*/

    void task1 ();void task2 ();

    void task3 ();struct Task_st

    {

    int id;int pr;

    int en;};

    struct Task_st Tsks[3];

    void task1(){

    printf("Task 1 running\n");

    return;}

    void task2(){

    printf("Task 2 running\n");return;

    }

    void task3(){

    printf("Task 3 running\n");return;

    }int main(){

  • 8/8/2019 C Programming by Example

    31/33

    int state,j,counter=0;//Creating task table

    Tsks[0].id=1;Tsks[1].id=2;

    Tsks[2].id=3;

    //Creating priority list

    Tsks[0].pr=1;Tsks[1].pr=1;Tsks[2].pr=1;

    //Enable Tasks

    Tsks[0].en=1;Tsks[1].en=1;

    Tsks[2].en=1;

    while(1){

    counter++;// Scheduler routine

    for(state=0;state

  • 8/8/2019 C Programming by Example

    32/33

    There are a number of other mechanisms commonly used in RTOSs, passing data by

    reference, setting flags to indicate events and posting data in "mailboxes" are just

    some of them. The use of multi-core processors has brought on a new revolution in

    concurrent programming and C++ is now being used in various ways to support the

    programmer -www.openmp.org and Intel have now acquired a software house

    dedicated to this problem. RTOS suppliers provide tools that support multitaskingand more importantly, the debugging process in this environment :

    http://www.ghs.com/products/TI_davinci_development.html

    http://www.qnx.com/news/pr_3361_1.html

    http://www.embeddeddesignindia.co.in/ART_8800535482_2800002_TA_3d44a76

    2.HTM

    Exercise 6.2

    Write a single paragraph summary of the situation for RTOSs in multi-core

    systems. (max 200 words)

  • 8/8/2019 C Programming by Example

    33/33

    SECTION 7 : The Pin Ball Assignment

    This assignment requires you develop a game program that displays as Pin Ball

    game. Using the skills that you have already acquired, and the code examples,

    develop a program that has the following characteristics:

    a) The ball bounces off all sides of the game area, displaying some random

    characteristics.

    b) The ball bounces off randomly placed pillars on the screen.

    c) The game finishes when the ball "falls" into a "hole". The score of hits on the

    pillars at that stage is shown. If it is higher than a recorded value then the user is

    invited to enter a name, and the new top score is recorded.

    d) Paddles at the base of the screen can be activated using left and right mouse keys.

    (see graphics.h and the "colorado" website.

    These add momentum to the ball (speed it up).

    e) The ball loses momentum over time and slows down, losing height on the playing

    area, unless accelerated by the paddles.

    f) If the ball loses all height, it rolls off the bottom of the game area and the game isover.

    These must be written up in a report and the final program demonstrated before the

    last laboratory session ends. Late work will be penalized. Do NOT copy work from

    others, duplicate work will result in penalties for all parties.

    Marks 60% [ 10% for each section a)-f) ]