Sunday 10 October 2010

Bat Detector Circuit This Bat Detector Circuit is authored by Chris Eve. Basic tests with a variety of salvaged electret microphones all showed good

Bat Detector Circuit

This Bat Detector Circuit is authored by Chris Eve. Basic tests with a variety of salvaged electret microphones all showed good response to 50kHz and beyond, the smaller the unit the better the response. My tests indicate that a small electret microphone has at least some response to 100kHz and that this response is reasonably "flat" to at least 50kHz.



The microphone I use is approximately 6mm in diameter and can be mounted within the body of a 3.5mm jack plug. Having the microphone socketed rather than fixed within the detector case is optional, but gives further opportunity to experiment with uni-directional or "Pressure Zone" modules (see below), or other microphones mounted remotely from the electronics.

This bat detector circuit to have better sensitivity, both in distance to a visible bat and in audio frequency, than some other published circuits using a 40kHz transducer with 4000x gain amplification, though the 40kHz transducer I used for the comparison may have a bearing on these results.

The high-pass filter is included purely to help eliminate the circuit being triggered by ambient noise. The filter is a 4-pole Chebychev with a very steep roll-off below 15kHz. There is virtually zero response at 10kHz and below. This type of circuit relies on the wanted signal being loud enough to trigger the CMOS counter, so the less unwanted signal that reaches the circuit the better. Whilst any of the basic circuits based around a 40kHz transducer will perform adequately for the detection of bats calling within that frequency range, which includes many of the more common species, this circuit will give much better indication of the presence of less-common bats that call at lower frequencies, around 20kHz, as well, hopefully, those at somewhat higher frequencies.

When used at dusk, when individual bats are still visible, pointing a unidirectional microphone at a solitary bat indicates a usable range of at least 100ft (30m). Bats actually call very loudly indeed ... it's probably a good job we cannot hear them, else they would keep us awake!


This circuit was built in a metal box, because that was what I had to hand, using point-to-point wiring on a ground-plane. Perforated strip-board should be perfectly adequate and probably a lot easier to fault-find should you make a mistake. I do not have nor intend to produce a pcb layout, so please do not ask for one, though if you should feel the need to produce one and have the inclination to share it I would be only too willing to include it (or a link to it) on this page. The circuit may be more susceptable to interference from electronic sources if built in a plastic container. Current consumption is around 15mA with no audio output, so a PP3 battery should last for several evenings unless you have got a lot of bats in your area. For regular or extended use, rechargeable batteries or an external power source would make sense. Note that the LM386 has an absolute maximum voltage of 15v (12v recommended), but the rest of the circuit is OK to 15v. Also be aware, if tempted to use a regulated supply incorporating a 78xx series regulator, that these do generate a lot of noise, so extra filtering could be necessary, especially on the microphone supply. Component choice for the high-pass filter section is critical for good results, close-tolerance low-noise resistors and capacitors should be used to achieve the expected performance. Similar low-noise components should also be used in the rest of the circuit, (no carbon resistors!), though the tolerances are less critical elsewhere.

Having the microphone and loudspeaker both mounted on/in the detector itself can result in unwanted feedback limiting the volume the speaker can be used at. With the microphone mounted on the detector, simply handling the unit can cause audio output, though this can be reduced to a minimum if the unit is held firmly and moved gently. Remote mounting of the speaker and/or microphone, the use of a uni-directional microphone module (also helpful to determine where the bat is or for listening to an individual bat), or at least having the speaker facing away from the microphone, all help reduce/eliminate feedback, making it easier to share the experience with others.

Source: Bat Detector Circuit
See more : Oxygen Sensor

UltraSonic Radar [Ultrasonic Radar Circuit Board 2] This is a ultrasonic radar project with many practical applications in security and alarm systems


This is a ultrasonic radar project with many practical applications in security and alarm systems for homes, shops and cars. It consists of a set of ultrasonic receiver and transmitter which operate at the same frequency. When something moves in the area covered by the circuit the circuit’s fine balance is disturbed and the alarm is triggered. The circuit is very sensitive and can be adjusted to reset itself automatically or to stay triggered till it is reset manually after an alarm.




Adjustments
This kit does not need any adjustments, if you follow the building instructions.

Warning
If they are used as part of a larger assembly and any damage is caused, our company bears no responsibility.

While using electrical parts, handle power supply and equipment with great care, following safety standards as described by international specs and regulations.

If it does not work
Check your work for possible dry joints, bridges across adjacent tracks or soldering flux residues that usually cause problems. Check again all the external connections to and from the circuit to see if there is a mistake there.

See that there are no components missing or inserted in the wrong places.
Make sure that all the polarised components have been soldered the right way round. Make sure that the supply has the correct voltage and is connected the right way round to your circuit. Check your project for faulty or damaged components.

If everything checks and your project still fails to work, please contact your retailer and the Smart Kit Service will repair it for you.

Parts List
R1 = 180 KOhm C1, 6 = 10uF/16V TR1, 2, 3 = BC547 , BC548
R2 = 12 KOhm C2 = 47uF/16V P1 = 10 KOhm trimmer
R3, 8 = 47 KOhm C3 = 4,7 pF P2 = 47 KOhm trimmer
R4 = 3,9 KOhm C4, 7 = 1 nF IC1, 2 = 741 OP-AMP
R5, 6, 16 = 10 KOhm C5 = 10nF IC3 = 4093 C-MOS
R7, 10, 12, 14, 17 = 100 KΩ C8, 11 = 4,7 uF/16V R = TRANSDUCER 40KHz
R9, 11 = 1 MOhm C9 = 22uF/16V T = TRANSDUCER 40KHz
R13, 15 = 3,3 KOhm C10 = 100 nF D1, 2, 3, 4 = 1N4148
C12 = 2,2 uF/16V
C13 = 3,3nF
C14 = 47nF


Source: UltraSonic Radar
See More : Audio Detector

Lie Detector Circuit #2 This lie detector circuit can be built in a few minutes, but can be incredibly useful when you want to know if someone is rea

Lie Detector Circuit #2

This lie detector circuit can be built in a few minutes, but can be incredibly useful when you want to know if someone is really telling you the truth. It is not as sophisticated as the ones the professionals use, but it works. It works by measuring skin resistance, which goes down when you lie.



Parts List:

R1 - 33K 1/4W Resistor
R2 - 5K Pot
R3 - 1.5K 1/4W Resistor
C1 - 1uF 16V Electrolytic Capacitor
Q1 - 2N3565 NPN Transistor
M1 - 0-1 mA Analog Meter
MISC - Case, Wire, Electrodes (See Notes)

Notes:
  1. The electrodes can be alligator clips (although they can be painful), electrode pads (like the type they use in the hospital), or just wires and tape.
  2. To use the circuit, attach the electrodes to the back of the subjects hand, about 1 inch apart. Then, adjust the meter for a reading of 0. Ask the questions. You know the subject is lying when the meter changes.

Source: Lie Detector circuit
See more : Oxygen Sensor Simulator

Saturday 9 October 2010

PHP Tutorial: Writing A Feedback Form Script Getting Started with PHP: Write a FormMail Script in PHP

PHP Tutorial: Writing Your First PHP Script: Feedback Form Script

by Christopher Heng, thesitewizard.com

I have always believed that the most fun way to learn a new programming language, whether it is a language like C or a scripting language like PHP, is to use it to write a real-life useful program. Of course this is not the most systematic method of learning, but it works well if you already have some background in programming.

Preliminaries

  1. Before you write your first PHP program, make sure that that your website is running on a web host that runs PHP 4.1 or above.

  2. You may also find it useful to have a copy of PHP 4.1 or later installed on your own computer. This makes testing your PHP scripts much easier. If you use Windows, you can find some tips on installing PHP on your own computer from my article on "How to Install and Configure PHP 5 to Run with Apache on Windows" at http://www.thesitewizard.com/php/install-php-5-apache-windows.shtml

  3. And of course, you will need an ASCII text editor of some kind (such as Notepad on Windows). There's a list of such editors on http://www.thefreecountry.com/programming/editors.shtml

  4. This tutorial also assumes that you have at least some knowledge of HTML. This is necessary because if I have to explain all the HTML tags as well, this tutorial will end up being tediously long.

  5. You'll probably need a bit of programming background, or at the very least, an aptitude for computer programming. Note that being able to code in HTML does not count, since HTML is not a programming language. Unlike the majority of the other articles on thesitewizard.com, this article is not targeted at the absolute newcomer. You really need background in both web design using HTML and a bit of programming skill/aptitude, otherwise this article will be indecipherable. If you are reading this article because you want to create a website, please start with How to Make / Create Your Own Website: The Beginner's A-Z Guide instead.

I will begin with a very rudimentary (but working) PHP script to take input from a feedback form and send it to you in an email message. This type of form is sometimes referred to as a FormMail or Form to Mail script. In later articles, I will develop that script (and others) to include features commonly found in such FormMail scripts.

If you are programming-savvy, you will recognize this as a sort of "Hello World" program, but infinitely more useful!

Writing the Feedback Form

The first thing we need to do is to write the feedback form itself. Put the following code in the section of an HTML file named, say, feedback.html.

Email:
Message:

Basically the form asks the visitor for his email address (the field named "email" found in input name="email" above) and message (the field named "message" found in textarea name="message"), and presents him with a button which he can click to submit the contents of the form. When the form is submitted, it is "posted" (see the "method" attribute of the

tag) to a script named "sendmail.php" (also specified in the tag).

The Feedback Form PHP Script

Now all that remains is to code "sendmail.php". This is made extremely easy by the facilities available in PHP. Type the following code into a file named "sendmail.php". Do not put anything else into that file, ie, don't put in any other HTML tags or headers, etc.

 

When the form is submitted to sendmail.php, the contents of the "email" field in the form is put into a PHP variable called $_REQUEST['email']. Likewise the contents of the "message" field is put into the variable $_REQUEST['message'].

If you had named the fields in your form "emailofsender" and "contentsofmessage", then the information submitted in those fields would have been available to your script in the variables $_REQUEST['emailofsender'] and $_REQUEST['contentsofmessage'] respectively. I think you get the idea.

The first thing we do in our PHP script is to make the information that is submitted easily accessible to the rest of the program.

Firstly, we made a copy of the contents of $_REQUEST['email'] in a variable we call $email. This was done in the line

$email = $_REQUEST['email'] ;

Note that we don't really have to call this new variable $email. We could have called it $thingamajig if we wished, but it makes sense to name a variable with some meaningful name.

Likewise, in the next line, we made a copy (assigned) of $_REQUEST['message'] in a variable $message.

$message = $_REQUEST['message'] ;

Again, we could have named the new variable anything we wanted — but it's easier for us to understand the program if the variable name reflects what it does.

The real workhorse of this script is in the line beginning with "mail".

mail( "yourname@example.com", "Feedback Form Results",   $message, "From: $email" ); 

mail is a special function in PHP that sends mail. The first parameter to mail is supposed to contain the email address you want the form contents to be sent to, such as your own email address. The second parameter is the "Subject" of the email message. The last two parameters are the content of the message and the headers you want sent, respectively. We want a "From" header so that we know who is sending the email to us and can reply to him/her if we need to.

Notice that, like many other programming languages, strings (sequences of characters) are enclosed in double quotes, such as "Feedback Form Results".

Variables like $message can be used as-is. Note also that you can also interpolate (introduce) the contents of the variable $email into a string, like "From: $email", so that if your $email string contained an address like "william@shakespeare.com", the final string that is passed to the mail function will be "From: william@shakespeare.com".

You can also use single quotes (such as those in 'Hi there') to quote strings, but when you do so, the variables included are not expanded. This is useful if, for some reason, you really want to pass the string 'From: $email' to mail without PHP translating that to "From: william@shakespeare.com".

Finally, it is appropriate to thank the visitor for his message. This is done with the line

header( "Location: http://www.example.com/thankyou.html" );

This line causes PHP to send an HTTP header back to the visitor's browser telling it to load the URL "http://www.example.com/thankyou.html". The "header" function allows us to send any HTTP header to the browser.

You will of course have to create such a file called "thankyou.html" with some sort of message to thank your visitor for his efforts, otherwise your visitor will be greeted with an unfriendly "404 File Not Found" error after he sends his message. You should also replace the URLs and email addresses with the correct ones if you want to use that script on your site.

By the way, the script has to be enclosed within the "" and "?>" tags because the PHP processor treats all input as HTML code unless otherwise specified. On most systems, you can simply use "" and "?>" as the opening and closing tags to get the script to work, however if you want to be sure that your script will work on all systems, you should use the full "" form for the opening tag.

Easy wasn't it? In just a few lines, you've written your first PHP script. And it's not some trivial and useless script — it is actually a working, usable program.

Before you put the script "live" on the Internet, check out the following additional tutorials:

  • In How to Improve Your Form to Mail Script, you will develop the script so that your visitor's input is checked to catch instances where someone accidentally clicks the "Submit" button before they fill in their email address. You will also learn how to integrate both the form and the script into a single "feedback.php" file if you wish.

  • The article How to Prevent Email Injection in Your PHP Form to Mail Scripts deals with the security aspects of putting a PHP form to mail script "live" on the Internet, where spammers can abuse it and hijack it to send spam to others.

Copyright 2000-2010 by Christopher Heng. All rights reserved.

Get more free tips and articles like this, on web design, promotion, revenue and scripting, from http://www.thesitewizard.com/

Sunday 29 August 2010

Find the Shortest Path in C

#include <>
#include <>

#define INF 9999

void main( )
{
int arr[4][4] ;

int cost[4][4] = {
7, 5, 0, 0,
7, 0, 0, 2,
0, 3, 0, 0,
4, 0, 1, 0
} ;
int i, j, k, n = 4 ;

clrscr( ) ;

for ( i = 0 ; i < n ; i++ )
{
for ( j = 0; j < n ; j++ )
{
if ( cost[i][j] == 0 )

arr[i][j] = INF ;

else

arr[i][j] = cost[i][j] ;
}
}

printf ( "Adjacency matrix of cost of edges:\n" ) ;
for ( i = 0 ; i < n ; i++ )
{
for ( j = 0; j <>

printf ( "%d\t", arr[i][j] ) ;

printf ( "\n" ) ;
}

for ( k = 0 ; k < n ; k++ )
{
for ( i = 0 ; i < n ; i++ )
{
for ( j = 0 ; j < n ; j++ )
{
if ( arr[i][j] > arr[i][k] + arr[k][j] )

arr[i][j] = arr[i][k] + arr[k][j];
}
}
}

printf ( “\nAdjacency matrix of lowest cost between the vertices:\n” ) ;
for ( i = 0 ; i < n ; i++ )
{
for ( j = 0; j <>

printf ( “%d\t”, arr[i][j] ) ;

printf ( “\n” ) ;
}

getch( ) ;
}

Function Calls and Stack

By far the most widely used storage mediums are the floppy disks and the fixed disks (hard disks). Floppy disks and hard disks come in various sizes and capacities but they all work basically in the same way – information is magnetically encoded on their surface in patterns. These patterns are determined by the disk drive and the software that controls the drive.

Although the type of storage device is important, it is the way the stored information is laid out and managed that concerns programmers most. Therefore we would focus our attention on how information is organized and stored on the disk.

The Disk Structure

As most of us know, the disk drives in DOS and Windows are organized as zero-based drives. That is, drive A is drive number 0, drive B is drive number 1, drive C is drive number 2, etc. The hard disk drive can be further partitioned into logical partitions. Each drive consists of four logical parts-Boot Sector, File Allocation Table (FAT), Directory and Data space. Of these, the Boot Sector contains information about how the disk is organized. That is, how many sides does it contain, how many tracks are there on each side, how many sectors are there per track, how many bytes are there per sector, etc. The files and the directories are stored in the Data Space. The Directory contains information about the files like its attributes, name, size, etc. The FAT contains information about where the files and directories are stored in the data space.

When a file/directory is created on the disk, instead of allocating a sector for it, a group of sectors is allocated. This group of sectors is often known as a cluster. How many sectors together form one cluster depends upon the capacity of the disk. As the capacity goes on increasing, so also does the maximum cluster number. Accordingly, we have 12-bit, 16-bit or 32-bit FAT. In a 12-bit FAT each entry is of 12 bits. Since each entry in FAT represents a cluster number, the maximum cluster number possible in a 12-bit FAT is 212 (4096). Similarly, in case of a 16-bit FAT the maximum cluster number is 216 (65536). Also, for a 32-bit FAT the maximum cluster number is 228 (268435456. Only 28 of the 32 bits are used in this FAT). All FAT systems are not supported by all versions of Windows. For example, the 32-bit FAT system is supported only in Win 95 OSR2 version or later. There are differences in the organization of contents of Boot Sector, FAT and Directory in FAT12/ FAT16 system on one hand and FAT32 on the other.

The File Allocation Table

The File Allocation Table (FAT) maps the usage of the data space of the disk. It contains information about the space used by each individual file, the unused disk space and the space that is unusable due to defects in the disk. Since FAT contains vital information, two copies of FAT are usually stored on the disk. In case one gets destroyed, the other can be used. A typical FAT entry can contain any of the following:

- Unused cluster
- Reserved cluster
- Bad cluster
- Last cluster in the file
- Next cluster number in the file

There is one entry in the FAT for each cluster in the file area. If the value in a FAT entry doesn’t mark an unused, reserved or defective cluster, then the cluster corresponding to the FAT entry is part of a file, and the value in the FAT entry would indicate the next cluster in the file.
This means that the space that belongs to a given file is mapped by a chain of FAT entries. Each FAT entry points to the next entry in the chain. The first cluster number in the chain is the starting cluster number in the file’s directory entry. When a file is created or extended, a cluster is allocated to the file by searching the FAT for unused clusters and adding them to the chain. Vice versa, when a file is deleted, the cluster that has been allocated to the file is freed by clearing corresponding FAT entries (by setting them to 0). The FAT chain for a file ends with an entry FFFFh in the FAT.

This file occupies cluster number 3, 5, 6 and 8 on the disk. Hence the starting cluster number in the directory entry for the file is 3. Suppose this file is to be loaded into memory then OS would first load starting cluster number-3’s contents into memory. To find out the next cluster belonging to this file OS looks at entry number 3 in FAT where it finds a value 5. Therefore, now it loads the contents of cluster number 5 into memory. Once again OS looks at the FAT and finds in entry number 5 a value 6, hence it loads the contents of cluster 6 into memory. This process goes on till the OS finds an entry FFFFh in FAT, which indicates that there are no more clusters belonging to the file. Hence the process stops.

Now that we have understood how the FAT chain is traversed, let’s dig a little deeper into the FAT. The entries present in FAT are 12, 16 or 32 bits long depending on the storage capacity of the disk. Though a 12-bit FAT can handle 4096 clusters only 4078 clusters are available for use since some values are reserved. Similarly, for a 16-bit FAT out of the possible 65536 clusters that it can handle only 65518 are available for use.

In a 12-bit FAT three bytes form two entries. The first two entries (0 and 1) in the FAT are reserved for use by the OS. This means that first 3 bytes in a 12-bit FAT, first 4 bytes in 16-bit FAT and first 8 bytes in a 32-bit FAT are not used for storing cluster numbers. Out of these 3 or 4, or 8 bytes, the first byte is the media descriptor byte and the balance contains the value FFh. These balance bytes remain unused. The media descriptor byte specifies the type of the disk. It typically has a value FDh, F9h, F0h, F8h for a 360 KB, 1.2 MB, 1.44 MB and a hard disk respectively. The contents of a FAT entry are interpreted as shown below.

————————————————————————————
Values | Meaning |
————————————————————————————
12-bit | 16-bit | 32-bit | |
000h | 0000h | 0000000h | Cluster available |
FF0h-F6h | FFFFh-FFFF6h | FFFFFFFh-FFFFFF6h | Reserved cluster |
FF7h | FFF7h | FFFFFF7h | Bad cluster if not part of chain |
FF8h-FFh | FFF8h-FFFFh | FFFFFF8h-FFFFFFh | Last cluster of file |
xxx | xxxx | xxxxxxx | Next cluster in file |
————————————————————————————

Meaning of FAT entries

As we saw earlier, two identical copies of FAT are maintained on the disk. All copies are updated simultaneously whenever files are modified. If access to a FAT fails due to a read error, the OS tries the other copy. Thus, if one copy of the FAT becomes unreadable due to wear or a software accident, the other copy may still make it possible to salvage the files/directories on the disk.

Here is a program that prints the contents of the first sector of two copies of FAT for a 12-bit or a 16-bit FAT. On similar lines it can be extended to work for a 32-bit FAT.

Each disk contains two copies of FAT. In the function fat_info( ) the starting sector of each copy of FAT is determined. Next, the function read_fat_info( ) is called for reading and displaying contents of each FAT copy. Since each copy contains several entries, we have displayed only the first 16 entries for a 12-bit & 16-bit FAT. The organization of the FAT types is shown in Figure 7.3.

12-bit FAT

8 bits 8 bits 8 bits

E2 E3 O3 E1 O1 O2

16-bit FAT

8 bits 8 bits 8 bits 8 bits

E3 E4 E1 E2 O3 O4 O1 O2

32-bit FAT

8 bits 8 bits 8 bits 8 bits 8 bits 8 bits 8 bits 8 bits


E7 E8 E5 E6 E3 E4 E1 E2 O7 O8 O5 O6 O3 O4 O1 O2

For a 32-bit FAT the seven nibbles (a nibble is a group of 4 bits) E1-E2-E3-E4-E5-E6-E7-E8 form the even entry. Note that the arrangement of these nibbles is E7-E8-E5-E6-E3-E4-E1-E2 because the lower byte is always stored in memory earlier than the higher byte. This means if the value of the 4-byte FAT entry is ABCD, it would be stored as DCBA. The odd entry is represented using the set of nibbles O1-O2-O3-O4-O5-O6-O7-O8. In reality the nibble E8 and O8 don’t contribute to the cluster number since each entry in the 32-bit FAT is only 28 bits long.

On similar lines in a 16-bit FAT the four nibbles E1-E2-E3-E4 form the even entry whereas the set O1-O2-O3-O4 form the odd entry. Similarly, the even and odd entries in a 12-bit FAT are formed by E1-E2-E3 and O1-O2-O3 respectively. Picking up the values present in odd or even entries from a 32-bit FAT or a 16-bit FAT a relatively simple job. However, to pick up the values from a 12-bit FAT we have to use bitwise operators to discard one nibble out of a group of 4 nibbles. This is done in our program through the functions getfat_12( ).

/* File allocation table */

#include <>
#include <>
#include <>
#include <>
#include <>

struct boot
{
unsigned char jump[3] ;

char OEMname[8] ;

short int bps ;

unsigned char spc ;

short int reservedsec ;

unsigned char fatcopies ;

short int maxdirentries ;

short int totalsec ;

unsigned char mediadesc ;

short int secperfat ;

short int secpertrack ;

short int noofsides ;

long int hidden ;

long int hugesec ;

unsigned char drivenumber ;

unsigned char reserved ;

unsigned char bootsignature ;

long int volumeid ;

char volumelabel[11] ;

char filesystype[8] ;

unsigned char unused[450] ;

} ;

struct boot bs ;
char filetypestr[8] ;

void getfat_12 ( unsigned char * ) ;

void read_fat_info ( long ) ;

void fat_info( ) ;

void main( )
{
char choice ;

clrscr( ) ;

printf ( “A. Drive A” ) ;
printf ( “\nC. Drive C” ) ;
printf ( “\n0. Exit” ) ;

printf ( “\nEnter the drive (A/C): ” ) ;
scanf ( “%c”, &choice ) ;

if ( absread ( choice – 65, 1, 0, &bs ) == -1 )
{
printf ( “Error reading sector” ) ;
exit ( 0 ) ;
}
else
{
strcpy ( filetypestr, bs.filesystype ) ;
filetypestr[6] = ‘\0′ ;
}

fat_info( ) ;
}

void getfat_12 ( unsigned char *pfat )
{
int value ;
int *fatentry ;
int i, k ;

for ( k = 2 ; k < 18 ; k++ )
{
i = k * 3 / 2 ;

fatentry = ( int* ) ( pfat + i ) ;

if ( ( k % 2 ) == 0 )
value = ( *fatentry & 0x0fff ) ;
else
value = ( *fatentry > > 4 ) ;

printf ( “%03x “, value ) ;
if ( k % 9 == 0 )
printf ( “\n” ) ;
}
}

void read_fat_info ( long fat_num )
{
int j, i ;

unsigned char *p ;

if ( strncmp ( “FAT12″, filetypestr, 5 ) == 0 )
{
p = ( unsigned char* ) malloc ( bs.bps ) ;
absread ( 0, 1, fat_num, p ) ;
getfat_12( p ) ;
}

if ( strncmp ( “FAT16″, filetypestr, 5 ) == 0 )
{
short int *pfat ;
p = ( unsigned char* ) malloc ( bs.bps ) ;
absread ( 2, 1, fat_num, p ) ;
pfat = ( short int* ) p ;

for ( j = 0 ; j < 2 ; j++ )
{
printf ( “\n%d “, j * 8 ) ;
for ( i = 0 ; i < 8 ; i++ )
{
printf ( “%04x “, *pfat++ ) ;
}
}
}
}

void fat_info( )
{
long int first_fat, second_fat ;

first_fat = bs.reservedsec ;
second_fat = bs.reservedsec + bs.secperfat ;

printf ( “\n%s Fat Information”, filetypestr ) ;
printf ( “\n——————————-” ) ;

printf ( “\nFirst FAT Information\n” ) ;

read_fat_info ( first_fat ) ;

printf ( “\n\nSecond FAT Information\n” ) ;

read_fat_info ( second_fat ) ;
printf ( “\n——————————-\n” ) ;
}

VIA : http://www.c-cplusplus.com/fat-exploring-the-disk

Tower Of Hanoi in c

Tower of hanoi is a historical problem, which can be easily expressed using recursion. There are N disks of decreasing size stacked on one needle, and two other empty needles. Tower of hanoi is required to stack all the disks onto a second needle in the decreasing order of size. The third needle can be used as a temporary storage. The movement of the disks must confirm to the following rules,

1. Only one disk may be moved at a time
2. A disk can be moved from any needle to any other.
3. The larger disk should not rest upon a smaller one.

/* Program of towers of hanoi. */

#include <>
#include <>

void move ( int, char, char, char ) ;

void main( )
{
int n = 3 ;

clrscr( ) ;

move ( n, ‘A’, ‘B’, ‘C’ ) ;

getch( ) ;
}

void move ( int n, char sp, char ap, char ep )
{
if ( n == 1 )
printf (“\nMove from %c to %c “, sp, ep ) ;
else
{
move ( n – 1, sp, ep, ap ) ;
move ( 1, sp, ‘ ‘, ep ) ;
move ( n – 1, ap, sp, ep ) ;
}
}

Addition of two polynomials in c

#include
#include

#define MAX 10

struct term
{
int coeff ;
int exp ;
} ;

struct poly
{
struct term t [10] ;
int noofterms ;
} ;

void initpoly ( struct poly * ) ;
void polyappend ( struct poly *, int c, int e ) ;
struct poly polyadd ( struct poly, struct poly ) ;
void display ( struct poly ) ;

void main( )
{
struct poly p1, p2, p3 ;

clrscr( ) ;

initpoly ( &p1 ) ;
initpoly ( &p2 ) ;
initpoly ( &p3 ) ;

polyappend ( &p1, 1, 7 ) ;
polyappend ( &p1, 2, 6 ) ;
polyappend ( &p1, 3, 5 ) ;
polyappend ( &p1, 4, 4 ) ;
polyappend ( &p1, 5, 2 ) ;

polyappend ( &p2, 1, 4 ) ;
polyappend ( &p2, 1, 3 ) ;
polyappend ( &p2, 1, 2 ) ;
polyappend ( &p2, 1, 1 ) ;
polyappend ( &p2, 2, 0 ) ;

p3 = polyadd ( p1, p2 ) ;

printf ( “\nFirst polynomial:\n” ) ;
display ( p1 ) ;

printf ( “\n\nSecond polynomial:\n” ) ;
display ( p2 ) ;

printf ( “\n\nResultant polynomial:\n” ) ;
display ( p3 ) ;

getch( ) ;
}

/* initializes elements of struct poly */
void initpoly ( struct poly *p )
{
int i ;
p -> noofterms = 0 ;
for ( i = 0 ; i < MAX ; i++ )
{
p -> t[i].coeff = 0 ;
p -> t[i].exp = 0 ;
}
}

/* adds the term of polynomial to the array t */
void polyappend ( struct poly *p, int c, int e )
{
p -> t[p -> noofterms].coeff = c ;
p -> t[p -> noofterms].exp = e ;
( p -> noofterms ) ++ ;
}

/* displays the polynomial equation */
void display ( struct poly p )
{
int flag = 0, i ;
for ( i = 0 ; i < p.noofterms ; i++ )
{
if ( p.t[i].exp != 0 )
printf ( “%d x^%d + “, p.t[i].coeff, p.t[i].exp ) ;
else
{
printf ( “%d”, p.t[i].coeff ) ;
flag = 1 ;
}
}
if ( !flag )
printf ( “\b\b ” ) ;

}

/* adds two polynomials p1 and p2 */
struct poly polyadd ( struct poly p1, struct poly p2 )
{
int i, j, c ;
struct poly p3 ;
initpoly ( &p3 ) ;

if ( p1.noofterms > p2.noofterms )
c = p1.noofterms ;
else
c = p2.noofterms ;

for ( i = 0, j = 0 ; i <= c ; p3.noofterms++ )
{
if ( p1.t[i].coeff == 0 && p2.t[j].coeff == 0 )
break ;
if ( p1.t[i].exp >= p2.t[j].exp )
{
if ( p1.t[i].exp == p2.t[j].exp )
{
p3.t[p3.noofterms].coeff = p1.t[i].coeff + p2.t[j].coeff ;
p3.t[p3.noofterms].exp = p1.t[i].exp ;
i++ ;
j++ ;
}
else
{
p3.t[p3.noofterms].coeff = p1.t[i].coeff ;
p3.t[p3.noofterms].exp = p1.t[i].exp ;
i++ ;
}
}
else
{
p3.t[p3.noofterms].coeff = p2.t[j].coeff ;
p3.t[p3.noofterms].exp = p2.t[j].exp ;
j++ ;
}
}
return p3 ;
}

Add two Polynomials maintained as Linked Lists

C Program to add two polynomials maintained as linked lists.



#include <>
#include <>
#include <>

/* structure representing a node of a linked list. The node can store term of a polynomial */
struct polynode
{
float coeff ;
int exp ;
struct polynode *link ;
} ;

void poly_append ( struct polynode **, float, int ) ;
void display_poly ( struct polynode * ) ;
void poly_add ( struct polynode *, struct polynode *, struct polynode ** ) ;

void main( )
{
struct polynode *first, *second, *total ;
int i = 0 ;

first = second = total = NULL ; /* empty linked lists */

poly_append ( &first, 1.4, 5 ) ;
poly_append ( &first, 1.5, 4 ) ;
poly_append ( &first, 1.7, 2 ) ;
poly_append ( &first, 1.8, 1 ) ;
poly_append ( &first, 1.9, 0 ) ;

clrscr( ) ;
display_poly ( first ) ;

poly_append ( &second, 1.5, 6 ) ;
poly_append ( &second, 2.5, 5 ) ;
poly_append ( &second, -3.5, 4 ) ;
poly_append ( &second, 4.5, 3 ) ;
poly_append ( &second, 6.5, 1 ) ;

printf ( “\n\n” ) ;
display_poly ( second ) ;

/* draws a dashed horizontal line */
printf ( “\n” ) ;
while ( i++ < 79 )
printf ( "-" ) ;
printf ( "\n\n" ) ;

poly_add ( first, second, &total ) ;
display_poly ( total ) ; /* displays the resultant polynomial */
}

/* adds a term to a polynomial */
void poly_append ( struct polynode **q, float x, int y )
{
struct polynode *temp ;
temp = *q ;

/* creates a new node if the list is empty */
if ( *q == NULL )
{
*q = malloc ( sizeof ( struct polynode ) ) ;
temp = *q ;
}
else
{
/* traverse the entire linked list */
while ( temp - > link != NULL )
temp = temp – > link ;

/* create new nodes at intermediate stages */
temp – > link = malloc ( sizeof ( struct polynode ) ) ;
temp = temp – > link ;
}

/* assign coefficient and exponent */
temp – > coeff = x ;
temp – > exp = y ;
temp – > link = NULL ;
}

/* displays the contents of linked list representing a polynomial */
void display_poly ( struct polynode *q )
{
/* traverse till the end of the linked list */
while ( q != NULL )
{
printf ( “%.1f x^%d : “, q – > coeff, q – > exp ) ;
q = q – > link ;
}

printf ( “\b\b\b ” ) ; /* erases the last colon */
}

/* adds two polynomials */
void poly_add ( struct polynode *x, struct polynode *y, struct polynode **s )
{
struct polynode *z ;

/* if both linked lists are empty */
if ( x == NULL && y == NULL )
return ;

/* traverse till one of the list ends */
while ( x != NULL && y != NULL )
{
/* create a new node if the list is empty */
if ( *s == NULL )
{
*s = malloc ( sizeof ( struct polynode ) ) ;
z = *s ;
}
/* create new nodes at intermediate stages */
else
{
z – > link = malloc ( sizeof ( struct polynode ) ) ;
z = z – > link ;
}

/* store a term of the larger degree polynomial */
if ( x – > exp <> exp )
{
z – > coeff = y – > coeff ;
z – > exp = y – > exp ;
y = y – > link ; /* go to the next node */
}
else
{
if ( x – > exp > y – > exp )
{
z – > coeff = x – > coeff ;
z – > exp = x – > exp ;
x = x – > link ; /* go to the next node */
}
else
{
/* add the coefficients, when exponents are equal */
if ( x – > exp == y – > exp )
{
/* assigning the added coefficient */
z – > coeff = x – > coeff + y – > coeff ;
z – > exp = x – > exp ;
/* go to the next node */
x = x – > link ;
y = y – > link ;
}
}
}
}

/* assign remaining terms of the first polynomial to the result */
while ( x != NULL )
{
if ( *s == NULL )
{
*s = malloc ( sizeof ( struct polynode ) ) ;
z = *s ;
}
else
{
z – > link = malloc ( sizeof ( struct polynode ) ) ;
z = z – > link ;
}

/* assign coefficient and exponent */
z – > coeff = x – > coeff ;
z – > exp = x – > exp ;
x = x – > link ; /* go to the next node */
}

/* assign remaining terms of the second polynomial to the result */
while ( y != NULL )
{
if ( *s == NULL )
{
*s = malloc ( sizeof ( struct polynode ) ) ;
z = *s ;
}
else
{
z – > link = malloc ( sizeof ( struct polynode ) ) ;
z = z – > link ;
}

/* assign coefficient and exponent */
z – > coeff = y – > coeff ;
z – > exp = y – > exp ;
y = y – > link ; /* go to the next node */
}

z – > link = NULL ; /* assign NULL at end of resulting linked list */
}

read more: http://www.c-cplusplus.com/add-two-polynomials-maintained-as-linked-lists

C Data Structures source codes(Basic hash example)


Basic hash example

#include <>
#include <>

#define HASHSIZE 1000
#define MAXLINE 1024

typedef struct tnode {
char *data;
struct tnode *next;
} node;

void htable_init(node *hashtable); // fire up hashtable
void htable_insert(node *hashtable, char *str); // insert data into hashtable
void htable_resolve(node *hashtable, int loc, char *str); // resolve collisions in hashtable
void htable_display(node *hashtable); // display hashtable
int htable_delete(node *hashtable, char *str); // delete an entry from hashtable
int htable_hash(char *str); // hash data for hashtable

int main(void) {
char line[MAXLINE];
node *hashtable;

hashtable = (node *)malloc(HASHSIZE * sizeof(node));

htable_init(hashtable);

while((fgets(line, MAXLINE, stdin)) != NULL)
htable_insert(hashtable, line);

htable_display(hashtable);

return 0;
}

/* fire up hashtable */
void htable_init(node *hashtable) {
int i = 0;

for(i = 0; i < HASHSIZE; i++)
hashtable[i].data = NULL, hashtable[i].next = NULL;
}

/* insert data into hashtable */
void htable_insert(node *hashtable, char *str) {
int index = 0;

/*
// determine hash function
*/
index = htable_hash(str);
if(hashtable[index].data != NULL) {
/*
// collision occurs - resolve by chaining
*/
htable_resolve(hashtable, index, str);
} else {
hashtable[index].data = calloc(strlen(str) + 1, sizeof(char));
strcpy(hashtable[index].data, str);
}
}

/* hash data for hashtable */
int htable_hash(char *str) {
int index = 0;
char *tmp = NULL;

tmp = calloc(strlen(str) + 1, sizeof(char));
strcpy(tmp, str);

while(*tmp) {
index += *tmp;
tmp++;
}

index = index % HASHSIZE;
return index;
}

/* resolve collisions in hashtable */
void htable_resolve(node *hashtable, int loc, char *str) {
node *tmp;
tmp = hashtable + loc;

while(tmp->next != NULL)
tmp = tmp->next;
tmp->next = (node *)malloc(sizeof(node));
tmp->next->data = calloc(strlen(str) + 1, sizeof(char));
strcpy(tmp->next->data, str);
tmp->next->next = NULL;
}

/* display hashtable */
void htable_display(node *hashtable) {
int i = 0;
node *target;

for(i = 0; i < HASHSIZE; i++) {
if(hashtable[i].data != NULL) {
target = hashtable + i;
while(target)
/* printf("location: %d, data: %s", i, target->data), target = target->next; */
printf("%s", target->data), target = target->next;
} /* if */
} /* for */
}

/* delete an entry from hashtable */
int htable_delete(node *hashtable, char *str) {
node *bla;
node *blb;
char *tmp = NULL;
int index = 0;

index = htable_hash(str);

/* no item at this location */
if(hashtable[index].data == NULL)
return 1;

/* only one item at this location */
if(hashtable[index].next == NULL) {
if(strcmp(hashtable[index].data, str) == 0) {
/* item found */
tmp = hashtable[index].data;
hashtable[index].data = NULL;
free(tmp);
}
} else {
/* there is a chaining case */
bla = hashtable + index;
/* linked list similar */
while(bla->next != NULL) {
if(strcmp(bla->next->data, str) == 0) {
blb = bla->next;
if(bla->next->next)
bla->next = bla->next->next;
else
bla->next = NULL;

free(blb);
} /* if */
} /* while */
} /* else */

return 0;
}


Read more: http://cmagical.blogspot.com/2010/01/c-data-structures-source-codesbasic_2541.html#ixzz0y17voH00
Under Creative Commons License: Attribution Non-Commercial No Derivatives

Introduction to C and the PIC Microcontroller Introduction to C and the PIC Microcontroller



Real-World Interfacing



In this lab you will be introduced to the programming language C, and the PIC16F873, a popular and very widely used m-controller (read micro-controller). m-controllers find use in devices that needs some intelligence but not a huge amount of processing power (eg, fancy graphical interfaces, massive computing needs). You can find these devices in cars (engine control, anti-lock brakes...), in appliances, etc... There are many ways to program these devices, but you will be using C to program the PIC to perform some fairly simple tasks. C is often used with m-controllers because of its small size, high speed, and the access it allows to the real-world. This week you will get a short introduction to C as well as a brief look at some of the capabilities of the PIC.

A good resource for help with the PIC programmed with the CCS C-compiler is given at http://www.ccsinfo.com/forum/.

The PIC microcontroller comes in a wide range of variants. You can check them out in data books that are in the lab, or at the MicroChip web site. A m-controller is distinguished from a m-processor in that it has many capabilities useful for real-world interfacing built into the chip. The PIC has a RISC-based Harvard architecture with separate memory for data and program. The one we will be using is the PIC16F873 (link to data sheet) It has an on-board RAM (Random Access Memory), EPROM (Erasable Programmable Read Only Memory), an oscillator, a couple of timers, and several Input/Output (I/O) pins, serial ports and 8 channel A/D convertor (if you don’t know what all of those things are don’t worry; suffice it to say there can be an impressive array of peripherals built into the chip). However, the m-controller is less computationally capable than most m-processors due to the fact that they are used for simple control applications rather than spreadsheets and elaborate calculations. As an example, the PIC16F873 has 4096 words of memory for program, and only 192 bytes of RAM, and can only operate with clocks up to 20 MHz on 8 bits of data (compared to megabytes of RAM, Speeds of a GHZ or more and 32 or even 64 bits of data for many desktop systems). It also has no facilities for floating point numbers... A pinout of the PIC16F873 is shown below.



There are several pins that are used to power the device. Many of the other pins have multiple uses depending on how the device is programmed.

This week, and the next, you will be using a m-controller in the lab. These laboratories will serve as a brief introduction to the processor and to programming in C.



Getting started with C.

A simple C program

A very simple C program is shown below.

/*simple.c -- sets a pin low, then high*/
#INCLUDE <16f873.h> #USE DELAY (CLOCK=4000000)
void main() {   output_low(pin_C1);  output_high(pin_C1); }
This program has many common features of C programs. The first line is a comment that is ignored by the compiler. It is simply there to document what the program code does. A comment is anything that occurs between a "/*" and the subsequent "*/". The next line is a "directive". All directives begin with a "#" and are used to convey information to the compiler. The directive in this program tells the compiler to include a header file ("16F873.h") which is necessary when using the microcontroller’s input and output capabilities. The next two directives tell it how to configure the device, and how fast it goes. The next line tells the compiler that this is the "main" program, and that everything between the opening brace, {, and the matching closing brace, , constitutes the main program. The main program itself is only two lines. The first line (not a comment) is a call to the "output_low" function, which sets output pin pin_C1 low, and a call to output_high, which sets it high. . Note that after every program statement there is a semi-colon. This is very important.



Variables

Almost all programs will use variables which are simply units of information stored in the computers memory. The standard C language has a wide variety of variable types available, however the dialect we will be using is more restricted. The version of C that we will be using has a quite unstandard set of variable types that are suited to its architecture.

Type SpecifierSizeRange
unsigned8 bit unsigned0 to 255
unsigned int
int
char
int8
long16 bit unsigned0 to 65535
long int
int16
signed8 bit signed-128 to 127
signed int
signed int8
signed long16 bit signed-32768

to 32767
signed int8
int3232 bit unsigned4*109
signed int3232 bit signed±2*109
float32 bit floating point±0.5*2-128 to 1-(2-15)*2128
shortone bit0 to 1
short int
int1
The program below shows how variables are used.

#INCLUDE <16f873.h> #USE DELAY (CLOCK=4000000)
void main() {    char i, j, k; /* declare characters */
    i=2;     j=3;     k=i+j; }
Again we have a fairly simple program that shows many different features of C. Note the semicolon after every program statement. We declare 3 char’s, "i", "j" and "k". A char is simply an 8 bit variable. You should use chars whenever possible because the PIC is designed to work on data 8 bits at a time.



Numerical manipulations

C has a variety of built in operations for performing math. These are listed below along with an example where a=0x03, and b=0x11:

Name of OperandSymbolExampleResult a=0x03 b=0x11
Binary Operators (Two Operands)
Addition

+a+b0x14
Subtraction

-b-a0x0E
Multiplication

*a*b0x33
Division

/b/a0x05
Modulus

(remainder)

%b%a0x02
Bitwise and

&b&a0x01
Bitwise or

|b|a0x13
Bitwise xor

^b^a0x12
Shift right

>>b>>a0x02
Shift left

<<b<0x88
Unary Operators (One Operand)
increment

++++a0x04
decrement

----a0x03
negate

--a-0x03
logical complement

~~a0xFC


Logical Expressions

In addition ot manipulating numbers, C is also capable of handling logical expressions. When using these expressions TRUE is taken to be anything that is not zero, and FALSE is always equal to zero. Again, a=0x03, and b=0x11:

Binary operators (two operands)



Name of Operand

Symbol
Example

Result

a=0x03 b=0x11


Binary OperatorsGreater than>a>bFALSE
Less than

<aTRUE
Equal

==a==bFALSE
Greater than or equal

>=a>=bFALSE
Less than or equal

<=a<=bTRUE
Not equal

!=a!=bTRUE
Logical AND

&&a&&bTRUE
Logical OR

||a||bTRUE
Unary operators (one operand)

Logical complement

!!aFALSE




Manipulating addresses (somewhat advanced topic, may be skipped)

There are two operators used for manipulating addresses and you have already been briefly introduced to one of them, the indirection operator, *. The other one is the address operator &. If you have an address k, the value stored at that address is *k. If you have a variable j, the address of the variable is given by &j. Therefore it is obvious that *(&j)=j.



I/O (Input/Output) Ports

It is possible with with a PIC to interact with the real world. This is done thourgh the use of I/O ports. The PIC16F873 has 3 I/O ports, labeled "a", "b" and "c". We will use Port A for analog input, though it has other uses. Ports B and C will be used for digital I/O. On the schematic the pins are labeled RB0 through RB7, but the compiler refers to them as pin_B0 through pin_B7. Likewise for port C. The pins can be used for either input or output.

Your circuit has the pushbutton switch connected to RB0, and the LED's to pins RC0 through RC7.

Digital Output

There are several functions that are used for output from the PIC. A full listing is in the PCB manual. Four commonly used functions are:

  • Output_high(pin)

    Sets the specified pin to a logic 1 (about 5 volts).
  • Output_low(pin)

    Sets the specified pin to a logic 0 (about 0 volts)
  • Output_float(pin)

    Sets the specified pin to a high-impedance (or tri-state) state. In this state it is as if the pin has no connections to the chip. Current can neither go in or out of the pin.
  • Output_bit(pin, value)

    This function sets the specified pin to the specified value (which must be 0 or 1).
Digital Input

There is only one input function you will need for the PIC.

  • Input(pin)

    Reads the value on a specified pin. The value is returned in a short int. A proper use of the function would be something like:



    while( !input(pin_B0)) { ... }



    which would repeat the commands in the braces as long as RB0 was low.
"High level" I/O

If the PIC is connected to the PIC C development software via the debugger it is possible to do some higher level input and output. These interactions take place via the debugger's "Monitor" window.

You specify that IO is to take place through the debugger by properly defining serial connections (usually in your codes header file):

#use rs232(DEBUGGER)

You can then print to the monitor window by using "putc()" which sends a character to the monitor window, "puts()" which sends a string, or "printf()" which sends a formatted string. The "printf()" command is most useful, but also the most complicated (and takes the most memory).

The syntax of printf is the following:

printf(format-string, [arg_1] , ... , [arg_N] )
This is best illustrated by some examples.

Printing Examples

Example 1: Printing a message. The following statement prints a text string to the screen.

printf("Hello, world!\n");
In this example, the format string is simply printed to the screen.

The character \n at the end of the string signifies end-of-line. When an end-of-line character is printed, the LCD screen will be cleared when a subsequent character is printed. Thus, most printf statements are terminated by a \n.

Example 2: Printing a number. The following statement prints the value of the integer variable x with a brief message.

printf("Value is %d\n", x);
The special form %d is used to format the printing of an integer in decimal format.

Example 3: Printing a character. The following statement prints the ascii equivalent of the integer variable x with a brief message. Here is an ascii table.

printf("Value is %d, ascii = %c\n", x, x);
Example 4: Printing a number in binary. The following statement prints the value of the integer variable x as a binary number.

printf("Value is %b\n", x);
The special form %b is used to format the printing of an integer in binary format. Only the low byte of the number is printed.

Example 5: Printing a floating point number. The following statement prints the value of the floating point variable n as a floating point number.

printf("Value is %f\n", n);
The special form %f is used to format the printing of floating point number.

Example 6: Printing two numbers in hexadecimal format.

printf("A=%x  B=%x\n", a, b);
The form %x formats an integer to print in hexadecimal.

Formatting Command Summary

%d
Type: int Description: decimal number
%x
Type: int Description: hexadecimal number
%b
Type: int Description: low byte as binary number
%c
Type: int Description: low byte as ASCII character
%f
Type: float Description: floating point number
%s
Type: char array Description: char array (string)
Format CommandData TypeDescription
%dintdecimal number
%xinthexadecimal number
%bintlow byte as binary number
%cintlow byte as ASCII character
%ffloatfloating point number
%schar arraychar array (string)


Your circuit has the pushbutton switch connected to RB0, and the LED's to pins RC0 through RC7.

Input

Unfortunately, you can only receive input from the keyboard one character at a time using the getc() command. Be aware:

  • getc() returns the ascii equivalent of the character entered into the keyboard.
  • the keyboard I/O is implemented in software on the PIC. That means, it won't receive input from the keyboard unless it is explicitly looking for it. Therefore, your program must stop in order to look for input from the keyboard. (Hardware communications could receive a character in the background, without requiring software support).
As an example, the following code gets the ascii value in k, converts to a number, and prints the number.

k=getc(); %Get ascii value of keyboard input.

k=k-'0'; %Subtract value of '0' to convert to number.

printf(" ... k=%d\n",k); %print the number.




Control of Flow

What you have learned up to this point has been useful but is of limited utility because it does not allow for decision making capabilities by the computer. C has a variety of mechanisms to control the flow of a program. These are listed below:

The if...then construct

if (logical expression) {

...statements...

}


If the logical expression is true then evaluate the statements between the braces. The following code sets RC1 if a is even.

if ((a%2) == 0) {

Output_high(pin_C1);

}


The if...then...else construct

if (logical expression) {

...if statements...

}

else {

...else statements...

}


If the logical expression is true then evaluate the "if" statements between the braces, otherwise execute the "else" statements. The following code decides if a number if is even or odd.

if ((a%2) == 0) {

Output_high(pin_C1);

}

else {

Output_low(pin_C1);

}


while (logical expression) {     ...statements... }
While the logical expression is true, the statments (of which there is an arbitrary number) between the braces is executed. The following code cycles through the even numbers from 0 to 9 (the variables must have been declared elsewhere in the program).

a=0; while (a<10) a="a+2;">


The for loop

for (initial condition; logical expression; change loop counter variable) {

...statements...

}


Set the initial condition, then while the logical expression is true execute the statement between the braces while changing the loop counter as specified once at the end of each loop. This code segment is functionally equivalent to the one for the "while" loop.

for (a=0; a<10; a=a+2) {

...statements...

}




The case...switch construct

Case..switch is used in place of a series of "if...else" clauses when a variable can take on several values. The "default" clause at the bottom takes care of any cases not covered explicitly.

switch (variable) {

case val1: ...statements 1...

break;


case val2: ...statements 2...

break;


case val3: ...statements 3...

break;


default: ...statements default...

break;


}



Functions

Often a series of instruction must be repeated over and over again. Instead of repeating the same operations repetitively it is useful to use a function that performs the repetitive operations. For instance to set a value on RC1 and then read from RB0 and set RC0 to that value, and returning the value of RB0 you might use a function called "RB0toRC0". (Note: this program isn't meant to be particularly useful, but to introduce the syntax for function declaration, and use).

/*simpleFunc.c -- to demonstrate function calls*/
#INCLUDE <16f873.h> #USE DELAY (CLOCK=4000000)
short int RB0toRC0(RC1val) short int RC1val; {    Output_bit(pin_C1, RC1val);  /*Set RC1 to the specified value*/    if (input(pin_B0)) {         /*Read RB0*/             Output_high(pin_C0);      /*If RB0 is high, RC0 set high*/    }     else {       Output_low(pin_C0);       /*else set RC0 low*/    }    return(input(pin_B0));       /*Return RB0*/ } 
void main() {    short int b;     b=RB0toRC0(1);    b=RB0toRC0(0); }
This program introduces some new constructs. The most obvious is the function "RB0toRC0" which is at the top. The first line of the function declares that the function returns a short int, and has one argument. The type of the argument is given before the function's opening brace. The body of the function (between the braces) outputs a value to RC1, and reads from RB0 and echos to RC1. The last line tells that compiler to return the value of RB0 to the calling function.

The function is called in the main program with different arguments. The first call would set RC1 high, and return the current value of RB0 to the variable "b". The next line would set RC1 low, and return the value of RB0 to the variable "b".

Wrapping up

You should now know enough to do some fairly simple things with the microcontroller. This has been a very brief introduction to C and did not even begin to touch the richness available with the language. If you would like to know more look in the manuals in the lab, or some of the books in the library.

Other Info

If you want to work with the LCD on the PICDEM2 Plus board, you will find that documentation ranges from poor to nonexistent. Some working code is here.

Code for the PICDEMlcd board is equally poor/nonexistent/incorrect. Some working code is here.




Read more: http://cmagical.blogspot.com/2010/01/introduction-to-c-and-pic.html#ixzz0y17VD9E0

Under Creative Commons License: Attribution Non-Commercial No Derivatives