Skip to main content
Visitor II
November 27, 2023
Question

Uart to int conversion

  • November 27, 2023
  • 1 reply
  • 2925 views

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.

    This topic has been closed for replies.

    1 reply

    Graduate
    November 27, 2023

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

    VYada.3Author
    Visitor II
    November 27, 2023

    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

    Graduate II
    November 27, 2023

    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