何同学JoseHe的个人网站

首页 注册 登录 文章

目录

    提取字符串string或ASCII中的数据,输出浮点数,信捷PLC C语言案例、tcp通讯案例

    背景

    在做通讯的时候,比如机器人、视觉发数据给PLC,经常发的是ASCII格式的一段数据,而PLC实际用的一般是int或float的数据,我们希望有一个智能的fc能提取ASCII里面的数据转成浮点数,何同学为此做了一个fc。


    通讯指令

    截图中HD2100是个首地址,接受客户端发过来的40个字节的ASCII数据。

    HD2100可以在自由监控中监控成ASCII格式。


    string_flt_fc

    截图中的数据怎么提取出来转为浮点数呢?


    此处采用FC,用C语言,输入的是ASCII的数据,输出浮点数,由FC智能提取与转换。


    C语言代码


    float str_to_float1 ( const char *str )
    {
    float result = 0.0f;
    float decimal = 0.1f;
    int sign = 1;
    int i = 0;

    if ( str[0] == '-' )
    {
    sign = -1;
    i++;
    }

    while ( str[i] >= '0' && str[i] <= '9' )
    {
    result = result * 10.0f + ( str[i] - '0' );
    i++;
    }

    if ( str[i] == '.' )
    {
    i++;
    while ( str[i] >= '0' && str[i] <= '9' )
    {
    result += ( str[i] - '0' ) * decimal;
    decimal *= 0.1f;
    i++;
    }
    }

    return result * sign;
    }

    int extract_floats1 ( const char *input, float *output, int max_count )
    {
    int count = 0;
    int len = strlen ( input );
    int start = -1;
    int i;

    for ( i = 0; i <= len; i++ )
    {
    char c = ( i < len ) ? input[i] : '\0';

    if ( ( c >= '0' && c <= '9' ) || c == '-' || c == '.' )
    {
    if ( start == -1 )
    {
    start = i;
    }
    }
    else
    {
    if ( start != -1 && count < max_count )
    {
    char num_str[32];
    int j;
    for ( j = 0; j < 31 && start + j < i; j++ )
    {
    num_str[j] = input[start + j];
    }
    num_str[j] = '\0';
    output[count++] = str_to_float1 ( num_str );
    start = -1;
    }
    }
    }

    return count;
    }
    void string_flt_fc ( INT input_string[20], REAL out_flt[10] )
    {
    #define SysRegAddr_HD_D_HM_M
    #define MAX_FLOATS 10
    float float_array[MAX_FLOATS];
    int float_count;
    //char input_str[] = "290.295,83.769,-46.707,-51.165,0.000,0.000;0,-1,0,1;0,0,0;0.000,0.000,0.000,0.000,0.000";
    // char *input_str = ( char * ) &HD[2100]; // 使用D0~D37存储字符串
    //char *input_str = ( char * ) &input_string;
    char *input_str = input_string;
    float_count = extract_floats1 ( input_str, float_array, MAX_FLOATS );

    out_flt[0] = float_array[0];
    out_flt[1] = float_array[1];
    out_flt[2] = float_array[2];
    out_flt[3] = float_array[3];



    }

    代码还是有一定难度,用到了C语言函数、数组、指针、for循环、if语句等知识点。


    案例程序下载

    0528提取字符串string转浮点数案例,网口自由格式, 服务器 - C语言FC版本.xdp

    返回文章列表

    评论

    发表评论

    请先登录后再发表评论

    评论列表

    暂无评论