Skip to main content
Associate
November 30, 2024
Question

How to receive a number, add a number to it and transmit it again?

I am trying to add 5 to the received number but I can't figure out what am I doing wrong.
This is the code from Keil

 

uint8_t receivedNumber;
uint8_t newNumber;

while(1){
if(HAL_UART_Receive_IT(&huart2,(uint8_t *)&receivedNumber,sizeof(receivedNumber))==HAL_OK)
{
 int newNumber=receivedNumber+5;
 HAL_UART_Transmit(&huart2,(uint8_t *)&newNumber,sizeof(newNumber),1000);
}
}

 

When it receives 1,2,3 or 4, it transmits 6,7,8,9 (as expected). When it receives 5 it transmits a " : "  and when it receives 11,21,37 or 42, it transmits 66,76,8< and 97.
Edit:5,6,7,8 to 6,7,8,9

This topic has been closed for replies.

3 replies

Peter BENSCH
ST Technical Moderator
November 30, 2024

Welcome @222student, to the community!

Please read through the coding of characters again (keyword ASCII table). What you are receiving are ASCII characters that cannot be readily calculated.

Incidentally, "5" is not an expected output if you have received "1" and add 5 - is it?

In any case, the (ASCII) character "1" is encoded in binary 0x31. If you add 5, you get 0x36, which corresponds to the character "6" in the ASCII table. However, if you receive, for example, the character "5" with the ASCII equivalent of 0x35, your calculation results in 0x3A, which stands for the character ":".

You must therefore pay attention to WHAT you are receiving and how it is to be INTERPRETED.

Regards

/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.
Associate
November 30, 2024

Thank you so much for the reply, I will look into it.

And yeah, I meant "6,7,8,9" not "5,6,7,8"

Tesla DeLorean
Guru
November 30, 2024

Perhaps ponder how integer number space vs ASCII works.

Look at sscanf() and sprintf()

Look at atoi() and itoa()

 

Tips, Buy me a coffee, or three.. PayPal Venmo (See Profile) Up vote any posts that you find helpful, it shows what's working..