Question

I don't understand what I am doing wrong here.

I opened UART with 9600 baud rate as following, I am using MPLAB XC8 compiler with PIC18F87J11.

#include <usart.h>
#define FOSC (8000000UL)
 #define FCYC (FOSC/4UL)
 #define BAUD 9600UL
 #define SPBRG_INIT (FOSC/(16UL*BAUD) - 1)
Open1USART(USART_TX_INT_OFF & USART_RX_INT_OFF & USART_ASYNCH_MODE & USART_EIGHT_BIT & USART_CONT_RX & USART_BRGH_HIGH, SPBRG_INIT);

This is how I echo what I type on the terminal

 while ( 1)
     {
          while(PIR1bits.RCIF == 0 );
          {
            message = Read1USART();
            Write1USART(message);

            while (!TXSTA1bits.TRMT);
              }

     }

However the following does not work. If message equals 12, I want to print 12 to the terminal but its never true. It only reads one character at time.

while ( 1)
     {
          while(PIR1bits.RCIF == 0 );
          {
            message = Read1USART();
            if (message == 12)
            {
            Write1USART(message);
            while (!TXSTA1bits.TRMT);
              }
          }
     }

How do I fix it so that it accepts more than one character (like 12)? Then output it to the terminal? Thanks!

Was it helpful?

Solution

I think you need to learn about the ASCII code. Bytes are just numbers between 0 and 255 and ASCII defines how those numbers map to printable (or non-printable) characters. The number 91, the number 0x61, and the character 'a' all mean the same thing in C.

When you typed '1' at your terminal program, it encoded it in ASCII as byte 49 (0x31) and sent it to your PIC. Then when you typed '2' at your terminal it encoded it as byte 50 (0x32) and sent it to your PIC.

If you want your PIC to look for a certain character, try using the character literals provided by the C language:

if (message == 'a')
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top