cancel
Showing results for 
Search instead for 
Did you mean: 

Uart to int conversion

VYada.3
Associate II

Hi

im hoping someone can help me, honestly it might be a easy thing to do, however i have been cracking my brain around this and can't seem to get it to work.

uint8_t Rx_data[6] = {0};

HAL_UART_Receive(&huart1, Rx_data, 6, 1000);
printf("%s\n", Rx_data);

above is my code that reads from the serial port and outputs the data of what has been passed to the microcontroller

*030,R
*023,A
*046,A
*015,R

above is what the data looks like and i need to get the numbers and convert them to a int so i can use them in a if statement as an example

if(5 > (int value){

//do something

}

if someone could help that would be great

Thank you

 

EDIT: Edited by ST Moderator to add the right Topics.

4 REPLIES 4
gbm
Lead III

Have you ever heard of a sscanf() function from C standard library? Or maybe atoi()?

My STM32 stuff on github - compact USB device stack and more: https://github.com/gbm-ii/gbmUSBdevice

hi

i havent scanf but have atoi. will look at scanf

i have got it to work using this

char string_var[100];
size_t bufflen = sizeof(Rx_data);
memcpy( string_var, Rx_data, bufflen );
string_var[bufflen] = '\0';
char *p = strtok(string_var, ",");
char *p2 = strtok(p, "*");

int speed = atoi(p2);

printf("%d\n", speed);

 

i feel as if there is an easier way

You can type cast it when you use strtok so you don't have to copy from your Rx_data to string_var. Since you only care for the number you can just use 1 pointer and "*" delimiter

uint8_t data[] = "*030,R";
    
int main()
{
    int speed;
    char *token;

    token = strtok((char*) data,"*");
    speed = atoi(token);
    
    printf("Speed:%d\n", speed);

    return 0;
}

// output
Speed:30

 

Tips and Tricks with TimerCallback https://www.youtube.com/@eebykarl
If you find my solution useful, please click the Accept as Solution so others see the solution.

>>i feel as if there is an easier way

To do what?

You seem to have realized that the UART does not return NUL terminated strings. Generally you don't want to use C string functions directly on memory buffers, especially when they are a physical size, and not constrained by NULs

I wouldn't use strtok() these days, it's not thread safe, I tend to use strsep() to decompose and parse strings as it is thread safe, ie not using a global stored by the function between usage.

sscanf() can pick multiple value out of a string, the library is large, and the data often doesn't fit the constraints of the "format" data pattern.

atoi() is pretty simple, the more high-school approach is to have an accumulator you multiply by 10 before you add in each new decimal digit, subtracting off the ASCII '0' offset.

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