You are currently viewing How to Receive a String From UART

How to Receive a String From UART

Spread the love

Many devices like GSM Modem; GPS Module sends several characters in reply to the commands provided. So instead of writing a serial port code which receives a character one by one, we can add a piece of code that receives a string and store it in an array. This will be useful when we search a string or compare a string (string manipulations). GSM modem will reply the string “OK” for almost every AT commands, if we already written to get a string, we can compare the string “OK” with the string stored already.

Here is an Example code that gets a string of characters via serial port

Note: Serial port is referred as RS232, UART, USART, synchronous, Asynchronous, Half-duplex, Full duplex communications.

 

Processor: dsPIC30F4011, Compiler: MPLAB C30,

#include <p30fxxxx.h>

 _FOSC(CSW_FSCM_OFF & XT);

_FWDT(WDT_OFF);

_FBORPOR(PBOR_ON & MCLR_EN);

_FGS(CODE_PROT_OFF);

 #define _XTAL_FREQ      10000000UL     //Crystal=10MHz,FOSC=XTAL*PLL

 #define FCY             (_XTAL_FREQ/4)      //add your operating frequency

#define BAUD_VAL(x)      (((FCY/(x))/16)-1)

 unsigned char Str[72];

 void UART1_Init(unsigned int BaudRate);

void UART1_Txmt(unsigned char data);

void UART1_Puts(const unsigned char *str);

void gets_UART1(unsigned char *string);

unsigned char UART1_Receive(void);

void DelayMs(unsigned int Ms);



int main(void)

{

DelayMs(10);

UART1_Init(9600);

DelayMs(1000);

UART1_Puts("Enter A String:\r\n");

while(1)

{

gets_UART1(Str);

UART1_Puts("The String Received is:");

UART1_Puts(Str);

UART1_Puts("\r\n");

}

}

void UART1_Init(unsigned int BaudRate)

{

U1BRG      =   BAUD_VAL(BaudRate);

U1MODE  =   0x8000;

U1STA       =    0x8400;

_U1TXIF=0;

UART1_Puts("\033[2J");           //Clear HyperTerminal

}

void UART1_Txmt(unsigned char data)

{

while(IFS0bits.U1TXIF==0);

U1TXREG=data;

IFS0bits.U1TXIF=0;

}

void UART1_Puts(const unsigned char *Str)

{

while(*Str)

UART1_Txmt(*Str++);

}



unsigned char UART1_Receive(void)

{

unsigned char c;

while(_U1RXIF==0);

_U1RXIF=0;

c = U1RXREG;

return c;

}

void gets_UART1(unsigned char *string)  //Receive a character until carriage return or newline

{

unsigned char i=0,J=0;

do

{

*(string+i)= UART1_Receive();

J = *(string+i);

i++;

}

while((J!='\n') && (J!='\r'));

i++;

*(string+i) = '\0';

}

https://www.pantechsolutions.net/microcontroller-boards/dspic-development-board

This Post Has 2 Comments

  1. mia mansoor

    THEN HOW TO RECEIVE STRING THROUGH UART INTERRUPT MECHANISM & DISPLAY IT IN LCD ?

    1. Pantech

      can u please provide the details of the microcontroller

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.