cancel
Showing results for 
Search instead for 
Did you mean: 

Receive a string 9 chars long through UART1

GGhed.1
Associate II

I would like to receive a string through the UART1,

its format is from 000000000 to 999999999,

However when I send the string only the first object is read and it is repeated nine times and the other values are lost.

I am using this function to read the data from UART

void Serial_read_char(uint8_t * buf, uint8_t numberOfBytes)
{
		buf[pos] = UART1_ReceiveData8();
		
		UART1_ClearITPendingBit(UART1_IT_RXNE);
		UART1_ClearFlag(UART1_FLAG_RXNE);
		
		pos++;
		
		if(pos > numberOfBytes)
		{
			pos = 0;
		}
 }

And this is how I am storing the data in the main function

		if (UART1_GetFlagStatus(UART1_FLAG_RXNE) == TRUE) 
		{
			Serial_read_char(buf, 9);
			delay_ms(1);
			
			get_lux = (*(buf+0) - 0x30)*100+
								(*(buf+1) - 0x30)*10 +
								(*(buf+2) - 0x30);
								
			get_warm =(*(buf+3) - 0x30)*100+
								(*(buf+4) - 0x30)*10 +
								(*(buf+5) - 0x30);
								
			get_cool =(*(buf+6) - 0x30)*100+
								(*(buf+7) - 0x30)*10 +
								(*(buf+8) - 0x30);
		}

How could I read correctly the value from the String?

I am using the STM8S208C6 and the Cosmic compiler free

2 REPLIES 2
Peter BENSCH
ST Employee

Please double-check your routines.

Where did you set the value of pos before calling Serial_read_char?

You are calling Serial_read_char with a parameter of 9 for the number of characters and you also reset the pos counter in that routine... but where is the loop to read the byte(s) there?

Good luck!

/Peter

In order to give better visibility on the answered topics, please click on Accept as Solution on the reply which solved your issue or answered your question.
GGhed.1
Associate II

@Peter BENSCH​ , thank you for the answer.

I was reading some forums about this issue and I notice that one solution was to use interrupt everytime that my system receives any data from the UART1.

I applied it into my code and it is working quite well.

This was the solution, I hope that it can help someone else that face the same problem:

extern unsigned char buf[9];
unsigned int pos = 0;
 
extern int get_lux;
extern int get_warm;
extern int get_cool;
 
#ifdef _COSMIC_
@far @interrupt void UART1_RX_IRQHandler(void)
#else /* _RAISONANCE_ */
void UART1_RX_IRQHandler(void) interrupt 18
#endif /* _COSMIC_ */
 
{
        buf[pos] = UART1_ReceiveData8();
	UART1_ClearITPendingBit(UART1_IT_RXNE);
	UART1_ClearFlag(UART1_FLAG_RXNE);
 
	if (pos >= 8)
	{
		get_lux = ((buf[0]) - 0x30 )*100+
			  ((buf[1]) - 0x30 )*10 +
		          ((buf[2]) - 0x30 );
 
		get_warm =((buf[3]) - 0x30 )*100+
		          ((buf[4]) - 0x30 )*10 +
		          ((buf[5]) - 0x30 );
	
		get_cool =((buf[6]) - 0x30 )*100+
		          ((buf[7]) - 0x30 )*10 +
			  ((buf[8]) - 0x30 );
		pos = 0;
	}
 
	pos++;
}