We are running a survey to help us improve the experience for all of our members. If you see the survey appear, please take the time to tell us about your experience if you can.
I was trying to make a program that would get a letter from the serial then add up all the numbers that follow it until the next letter appears in the serial port. I was using P2 for a visual aid only. Anyone know of a link I could go to so I could get on the right path.? #include <reg51.h> #include <stdio.h> unsigned int getchr(void); int tempval; int result; int X; void main(void) { X = 0x00; SCON = 0x50; TMOD = 0x20; TH1 = 0xFD; //9600 baud TR1 = 1; TI = 1; while (1) { P2 = 0; while (1) { tempval = getchr(); //GET CHAR FORM SERIAL PORT if(tempval == 0x58 && result != 0x58) //CHECK FOR "X" {result = 0x58; tempval = 0x00;} // CLEAR tempval if(result == 0x58 && tempval != 0x00) {X = X +(tempval - 0x30); // ADDS VALUE FROM X AND KEEPS ON ADDING EVEN IF A KEY //WHEN SERIAL DATA ISN'T COMING IN. tempval = 0x00;} // CLEAR tempval if(result == 0x5A) //CHECK FOR "Z" {X = 0x00; // CLEAR X result =0x00;} // ZERO P2 P2 = X; //SEND X TO PORT P2 } } } unsigned int getchr(void) { unsigned int chr, ch1; ch1 = 0x00; chr = 0x00; ch1 = SBUF; //GET CHARACTER chr = ch1 & 0x7f; //MASK OFF 8TH BIT RI = 0; //CLEAR STATUS return(chr); }
I was under the (perhaps subconcious) impression that getchr() would block until a character was available. But looking at your second implementation, it clearly doesn't wait. Depending on your goals, you probably want getchr() to wait for RI to become 1 (signalling a new character) before returning, in which case this problem should go away. Compare with Keil's implementation of getkey():
unsigned int getchr(void) { unsigned int chr; chr = SBUF; RI = 0; return(chr); } char _getkey () { char c; while (!RI); c = SBUF; RI = 0; return (c); }
Thank you for your help! I knew I was over looking something and that was the while (!RI); Thank you again, Glenn