Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*-----------------------------------------------------/
- Name : Mohd Syahri Fikri Bin Samusi
- [LAB02 Q05] KEYPAD 4x4 interfacing with
- PIC16F877A. A simple calculator, with
- divide by zero check.
- Date modified : 12 April 2012
- /-----------------------------------------------------*/
- #include <htc.h>
- #include <pic16f877a.h>
- #include <stdio.h>
- #include <stdlib.h>
- #include <usart.c>
- #define _XTAL_FREQ 20000000
- #include <KEYPAD_RB.c>
- void init_rs232( )
- {
- TRISC = TRISC | 0b10000000;
- BRGH = 1;
- SPBRG = 129; // set baud rate: Fosc=20Mhz, BR=9600
- TX9 = 0; // ninebits?1:0,,,8- or 9-bit transmission
- SYNC = 0; // asynchronous
- SPEN = 1; // enable serial port pins
- TXEN = 1; // enable the transmitter & (automatically)TXIF=1
- CREN = 1; // enable reception
- SREN = 0; // no effect
- TXIE = 0; // disable tx interrupts
- RCIE = 0; // disable rx interrupts
- }
- int isamong (char a, char *s)
- {
- while (*s)
- {
- if (a==*s++)
- {
- return 1;
- }
- }
- return 0;
- }
- void calc(char *op, long int *a, long int *b)
- {
- double ans;
- int f;
- if (*op=='+') //Performing addition
- {
- f=0;
- ans = *a + *b;
- }
- else if (*op=='-') //Performing subtraction
- {
- f=0;
- if (*a > *b)
- {
- ans = *a - *b;
- }
- else
- {
- ans = -1*(*b - *a);
- }
- }
- else if (*op=='*') //Performing multiplication
- {
- f=0;
- ans = *a * *b;
- }
- else if (*op=='/') //Performing division
- {
- if(*b==0)
- {
- f=1;
- }
- else
- {
- f=0;
- ans = *a *1.0 / *b;
- }
- }
- if(f==1)
- {
- printf ("\r\n ERROR!! Cannot divide by 0 \n");
- }
- else
- {
- printf ("\r\n%ld %c %ld \n= %f", *a, *op, *b, ans);
- }
- }
- void main( )
- {
- char k=0;
- long int a=0, b=0;
- int c=0,c1=0, d=0, e=0, op;
- kbd_init( ); //Initialize keypad
- init_rs232( ); //Initialize serial I/O
- printf ("\fReady...\r\n"); //Show the ready message
- while (1) //Keep running
- {
- if (kbd_getc( )==0)
- {
- do
- {
- k=kbd_getc( );
- __delay_ms(30);
- if (k>='0'&&k<='9')
- c1=1;
- else if (isamong(k,"+-/*C="))
- c1=1;
- else
- c1=0;
- }
- while(c1==0);
- }
- if(k!=0)
- {
- if(k=='C')
- {
- printf ("\r\nAgain...\n");
- c=0;
- d=0;
- }
- else
- {
- if(c==2)
- {
- printf ("\fReady...\n");
- c=0;
- }
- if(k!='=')
- {
- putch(k);
- if((k>='0')&&(k<='9'))
- {
- if(c==0)
- {
- if(d==0)
- {
- a = k - '0';
- d++;
- }
- else
- {
- a = (a*10)+(k-'0');
- d++;
- }
- }
- else
- {
- if(e==0)
- {
- b = k - '0';
- e++;
- }
- else
- {
- b = (b*10)+(k-'0');
- e++;
- }
- }
- }
- else
- {
- op = k;
- c = 1;
- }
- }
- else
- {
- calc(&op, &a, &b);
- c = 2;
- d = 0;
- e = 0;
- }
- }
- k=0;
- }
- }
- }//End of Program
Advertisement
Add Comment
Please, Sign In to add comment