Here is the code
#includeusing namespace std; int main() { int n; int sum = 0; int number; cout << "Enter the value for n: "; cin >> n; for (number=1; number<=(2*n); number+2) { sum = sum + number; } cout << "The sum of "; cout << n; cout << " is "; cout << sum << endl; return 0; }
Sunday, 3 April 2011
Write a program in C / C++ that calculate the summation of consecutive positive odd integers from 1 to n
Write a program in C to find the sum of odd numbers and even numbers from 1 to n
#include
void main()
{
int n,i;
int addeven=0;
int addodd=1;
printf("\nEnter a number\n");
scanf("%d",&n);
fflush(stdin);
for(i=2;i<=n;i++)
{
if(i%2==0)
addeven+=i;
else
addodd+=i;
}
printf("\nThe sum of odd numbers is %d \nThe sum of even numbers is %d\n",addeven,addodd);
}
write a program to find the sum of first n odd integers
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
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 ;
}
C Data Structures source codes(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
Getting started with C.
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.
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 Specifier Size Range unsigned 8 bit unsigned 0 to 255 unsigned int int char int8 long 16 bit unsigned 0 to 65535 long int int16 signed 8 bit signed -128 to 127 signed int signed int8 signed long 16 bit signed -32768
to 32767signed int8 int32 32 bit unsigned 4*109 signed int32 32 bit signed ±2*109 float 32 bit floating point ±0.5*2-128 to 1-(2-15)*2128 short one bit 0 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.
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:
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 OperandSymbol Example Result
a=0x03 b=0x11Binary Operators Greater than > a>b FALSE Less than< a TRUE Equal== a==b FALSE Greater than or equal>= a>=b FALSE Less than or equal<= a<=b TRUE Not equal!= a!=b TRUE Logical AND&& a&&b TRUE Logical OR|| a||b TRUE Unary operators (one operand) Logical complement! !a FALSE
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.
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 OutputThere 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 InputThere 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.
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 ofprintfis 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 characterExample 2: Printing a number. The following statement prints the value of the integer variable\nat 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, mostprintfstatements are terminated by a\n.xwith a brief message.printf("Value is %d\n", x);The special formExample 3: Printing a character. The following statement prints the ascii equivalent of the integer variable%dis used to format the printing of an integer in decimal format.xwith 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 variablexas a binary number.printf("Value is %b\n", x);The special form%bis 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 variablenas a floating point number.printf("Value is %f\n", n);The special form%fis 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%xformats an integer to print in hexadecimal.Formatting Command Summary
%d- Type:
intDescription: decimal number%x- Type:
intDescription: hexadecimal number%b- Type:
intDescription: low byte as binary number%c- Type:
intDescription: low byte as ASCII character%f- Type:
floatDescription: floating point number%s- Type:
char arrayDescription: char array (string)
Format Command Data Type Description %dint decimal number %xint hexadecimal number %bint low byte as binary number %cint low byte as ASCII character %ffloat floating point number %schar array char array (string) Your circuit has the pushbutton switch connected to RB0, and the LED's to pins RC0 through RC7.InputUnfortunately, you can only receive input from the keyboard one character at a time using the getc() command. Be aware:As an example, the following code gets the ascii value in k, converts to a number, and prints the number.
- 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).
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.
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 constructif (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 constructif (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 loopfor (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 constructCase..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;}
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".
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.
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
C Programming on Unix ( Creating menu driven environment in C in Unix)
#include
#include
#define ENTER 10
#define ESCAPE 27
void init_curses()
{
initscr();
start_color();
init_pair(1,COLOR_WHITE,COLOR_BLUE);
init_pair(2,COLOR_RED,COLOR_GREEN);
init_pair(3,COLOR_RED,COLOR_WHITE);
init_pair(4,COLOR_BLUE,COLOR_YELLOW);
init_pair(5,COLOR_BLUE,COLOR_CYAN);
curs_set(0);
noecho();
keypad(stdscr,TRUE);
}
void draw_menubar(WINDOW *menubar)
{
wbkgd(menubar,COLOR_PAIR(5));
waddstr(menubar,"File");
wattron(menubar,COLOR_PAIR(3));
waddstr(menubar,"(F1)");
wattroff(menubar,COLOR_PAIR(3));
wmove(menubar,0,10);
waddstr(menubar,"Edit");
wattron(menubar,COLOR_PAIR(3));
waddstr(menubar,"(F2)");
wmove(menubar,0,20);
wattroff(menubar,COLOR_PAIR(3));
waddstr(menubar,"Search");
wattron(menubar,COLOR_PAIR(3));
waddstr(menubar,"(F3)");
wmove(menubar,0,31);
wattroff(menubar,COLOR_PAIR(3));
waddstr(menubar,"Cursor ");
wattron(menubar,COLOR_PAIR(3));
waddstr(menubar,"(F4)");
wmove(menubar,0,43);
wattroff(menubar,COLOR_PAIR(3));
waddstr(menubar,"Compile");
wattron(menubar,COLOR_PAIR(3));
waddstr(menubar,"(F5)");
wattroff(menubar,COLOR_PAIR(3));
wmove(menubar,0,56);
waddstr(menubar,"Help");
wattron(menubar,COLOR_PAIR(3));
waddstr(menubar,"(F6)");
wattroff(menubar,COLOR_PAIR(3));
wmove(menubar,0,66);
waddstr(menubar,"Exit");
wattron(menubar,COLOR_PAIR(3));
waddstr(menubar,"(F7)");
}
WINDOW **draw_menu(int start_col)
{
int i;
WINDOW **items;
items=(WINDOW **)malloc(9*sizeof(WINDOW *));
items[0]=newwin(6,19,1,start_col);
wbkgd(items[0],COLOR_PAIR(2));
// box(items[0],ACS_VLINE,ACS_HLINE);
//wprintw(items[1],"new");
items[1]=subwin(items[0],1,17,2,start_col+1);
items[2]=subwin(items[0],1,17,3,start_col+1);
items[3]=subwin(items[0],1,17,4,start_col+1);
items[4]=subwin(items[0],1,17,5,start_col+1);
items[5]=subwin(items[0],1,17,6,start_col+1);
items[6]=subwin(items[0],1,17,7,start_col+1);
/// items[7]=subwin(items[0],1,17,8,start_col+1);
// items[8]=subwin(items[0],1,17,9,start_col+1);
/// for (i=1;i<9;i++)
wprintw(items[1],"Load",i);
wprintw(items[2],"New",i);
wprintw(items[3],"Save");
wprintw(items[4],"Save as");
wprintw(items[5],"Printer");
/// wprintw(items[],"FILE%d",i);
/// wprintw(item[1],"File%d",i);
// wbkgd(items[1],COLOR_PAIR(1));
wrefresh(items[0]);
return items;
}
WINDOW **draw_menu2(int start_col)
{
int i;
WINDOW **items;
items=(WINDOW**) malloc(9*sizeof(WINDOW*));
items[0]=newwin(5,19,1,start_col);
wbkgd(items[0],COLOR_PAIR(2));
items[1]=subwin(items[0],1,17,2,start_col+1);
items[2]=subwin(items[0],1,17,3,start_col+1);
items[3]=subwin(items[0],1,17,4,start_col+1);
items[4]=subwin(items[0],1,17,5,start_col+1);
items[5]=subwin(items[0],1,17,6,start_col+1);
items[6]=subwin(items[0],1,17,7,start_col+1);
wprintw(items[1],"Find");
wprintw(items[2],"Find and replace");
wprintw(items[3],"Repeat last find");
wprintw(items[4],"Goto line number");
wrefresh(items[0]);
return items;
}
WINDOW **draw_menu1(int start_col)
{
int i;
WINDOW **items;
items=(WINDOW**) malloc(9*sizeof(WINDOW*));
items[0]=newwin(6,19,1,start_col);
wbkgd(items[0],COLOR_PAIR(2));
items[1]=subwin(items[0],1,17,2,start_col+1);
items[2]=subwin(items[0],1,17,3,start_col+1);
items[3]=subwin(items[0],1,17,4,start_col+1);
items[4]=subwin(items[0],1,17,5,start_col+1);
items[5]=subwin(items[0],1,17,6,start_col+1);
items[6]=subwin(items[0],1,17,7,start_col+1);
wprintw(items[1],"Undo");
wprintw(items[2],"Cut");
wprintw(items[3],"Copy");
wprintw(items[4],"Paste");
wprintw(items[5],"Delete");
wrefresh(items[0]);
return items;
}
WINDOW **draw_menu4(int start_col)
{
int i;
WINDOW **items;
items=(WINDOW**) malloc(9*sizeof(WINDOW*));
items[0]=newwin(5,19,1,start_col);
wbkgd(items[0],COLOR_PAIR(2));
items[1]=subwin(items[0],1,17,2,start_col+1);
items[2]=subwin(items[0],1,17,2,start_col+1);
items[3]=subwin(items[0],1,17,4,start_col+1);
items[4]=subwin(items[0],1,17,4,start_col+1);
// items[5]=subwin(items[0],1,17,4,start_col+1);
// items[6]=subwin(items[0],1,17,4,start_col+1);
wprintw(items[2],"C Compiler");
wprintw(items[4],"C++ Compiler");
wrefresh(items[0]);
return items;
}
WINDOW **draw_menu5(int start_col)
{
int i;
WINDOW **items;
items=(WINDOW**) malloc(9*sizeof(WINDOW*));
items[0]=newwin(4,19,1,start_col);
wbkgd(items[0],COLOR_PAIR(2));
items[1]=subwin(items[0],1,17,2,start_col+1);
items[2]=subwin(items[0],1,17,2,start_col+1);
items[3]=subwin(items[0],1,17,2,start_col+1);
items[4]=subwin(items[0],1,17,4,start_col+1);
// items[5]=subwin(items[0],1,17,4,start_col+1);
// items[6]=subwin(items[0],1,17,4,start_col+1);
wprintw(items[2],"Key words");
// wprintw(items[4]," perator");
wprintw(items[4],"Operator");
// wprintw(items[6],"Help");
wrefresh(items[0]);
return items;
}
void delete_menu(WINDOW **items,int count)
{
int i;
for (i=0;i
delwin(items[i]);
free(items);
}
int scroll_menu(WINDOW **items,int count,int menu_start_col)
{
int key;
int selected=0;
while (1) {
key=getch();
if (key==KEY_DOWN || key==KEY_UP) {
wbkgd(items[selected+1],COLOR_PAIR(2));
wnoutrefresh(items[selected+1]);
if (key==KEY_DOWN) {
selected=(selected+1) % count;
} else {
selected=(selected+count-1) % count;
}
wbkgd(items[selected+1],COLOR_PAIR(1));
wnoutrefresh(items[selected+1]);
doupdate();
} else if (key==KEY_LEFT || key==KEY_RIGHT) {
delete_menu(items,count+1);
touchwin(stdscr);
refresh();
items=draw_menu(60-menu_start_col);
return scroll_menu(items,5,60-menu_start_col);
} else if (key==ESCAPE) {
return -1;
} else if (key==ENTER) {
return selected;
}
}
}
int main()
{
int key,t;
WINDOW *menubar,*messagebar,*window;
init_curses();
bkgd(COLOR_PAIR(1));
window=subwin(stdscr,1,80,24,0);
wbkgd(window,COLOR_PAIR(4));
menubar=subwin(stdscr,1,80,0,0);
messagebar=subwin(stdscr,1,79,23,1);
draw_menubar(menubar);
move(2,1);
printw("Press F1 or F2 to open the menus. ");
printw("F9 quits.");
/// window=newwin(2,68,23,8);
/// wbkgd(window,COLOR_PAIR(4));
///t=wgetch(window);
refresh();
do {
int selected_item;
WINDOW **menu_items;
key=getch();
werase(messagebar);
wrefresh(messagebar);
if (key==KEY_F(1))
{
menu_items=draw_menu(0);
selected_item=scroll_menu(menu_items,5,0);
delete_menu(menu_items,9);
if (selected_item<0)
wprintw(messagebar,
"You haven't selected any item.");
else
wprintw(messagebar, "You have selected menu item %d.",selected_item+1);
touchwin(stdscr);
refresh();
} else if (key==KEY_F(2))
{
menu_items=draw_menu1(10);
selected_item=scroll_menu(menu_items,5,10);
delete_menu(menu_items,9);
if (selected_item<0)
wprintw(messagebar,"You haven't selected any item.");
else
wprintw(messagebar, "You have selected menu item %d.",selected_item+1);
// touchwin(stdscr);
/// window=newwin(2,68,23,12);
///wbkgd(window,COLOR_PAIR(4));
/// t=wgetch(window);
touchwin(stdscr);
refresh();
}
else if(key==KEY_F(3))
{
menu_items=draw_menu2(20);
selected_item=scroll_menu(menu_items,5,20);
delete_menu(menu_items,9);
if(selected_item<0)
wprintw(messagebar,"don't select any item");
else
wprintw(messagebar, "You have select menu item %d",selected_item+1);
touchwin(stdscr);
refresh();
}
else if(key==KEY_F(5))
{
menu_items=draw_menu4(40);
selected_item=scroll_menu(menu_items,5,40);
delete_menu(menu_items,9);
if(selected_item<0)
wprintw(messagebar, "No item is selected");
else
wprintw(messagebar, "You have selected menu %d",selected_item+1);
touchwin(stdscr);
refresh();
}
else if(key==KEY_F(6))
{
menu_items=draw_menu5(55);
selected_item=scroll_menu(menu_items,5,55);
delete_menu(menu_items,9);
if(selected_item<0)
wprintw(messagebar,
" No item is selected");
else
wprintw(messagebar, "You have selected menu %d",selected_item+1);
touchwin(stdscr);
refresh();
}
else if(key==KEY_F(7))
{
menu_items=draw_menu4(60);
selected_item=scroll_menu(menu_items,5,60);
delete_menu(menu_items,9);
if(selected_item<0)
wprintw(messagebar, "No item is selected");
else
wprintw(messagebar, "You have to select menu %d",selected_item+1);
touchwin(stdscr);
refresh();
}
} while (key!=KEY_F(9));
delwin(menubar);
delwin(messagebar);
delwin(window);
endwin();
return 0;
}
Read more: http://cmagical.blogspot.com/2010/01/c-programming-on-unix-creating-menu.html#ixzz0y16dZleY
Under Creative Commons License: Attribution Non-Commercial No Derivatives