The string functions strstr and strchr from the c built in library string.h is very useful when we are looking for a particular string in an array of data received from UART.
The syntax are as follows:
strstr: strstr(x,y)
where x is the array which has a string of characters.
y is the string that we are looking for.
Example: strstr(x,”OK”)
This will return a pointer of first instance of string “OK” in x, otherwise a NULL
strchr: strchr(x,y)
where x is the array which has a string of characters.
y is a character that we are looking for.
Example: strstr(x,’N’)
This will return a pointer of first instance of character ‘N’ in x, otherwise a NULL
Processor: dsPIC30F4011, Compiler: MPLAB C30,
#include<p30fxxxx.h> #include<string.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(1) #define FCY (_XTAL_FREQ/4) //add your operating frequency #define BAUD_VAL(x) (((FCY/(x))/16)-1) unsigned char Str[72], *string_loc; 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(100); UART1_Puts("Enter A String and Hit Enter:\r\n"); while(1) { gets_UART1(Str); string_loc = strstr(Str,"OK"); if(string_loc) { UART1_Puts("String \"OK\" Found@:"); UART1_Puts(string_loc); } else UART1_Puts("String \"OK\" Not found"); 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); UART1_Txmt(J); i++; }while((J!='\n') && (J!='\r')); i++; *(string+i) = '\0'; UART1_Txmt('\r'); UART1_Txmt('\n'); } void DelayMs(unsigned int Ms) { unsigned int delay_cnst; while(Ms>0) { Ms--; for(delay_cnst = 0;delay_cnst <276;delay_cnst++); } }
https://www.pantechsolutions.net/microcontroller-boards/dspic-development-board