【问题标题】:Float into uint8_t arrayFloat into uint8_t array
【发布时间】:2022-12-01 23:11:59
【问题描述】:

I want to make 4 different ADC measurements. I want to be that those readed values are floats. After that I want to put those 4 float values in an uint8_t array to send it over a function.

After getting the sample value of the ADC I will make calculations to get the voltage. I read it out with a 12-bit adc.

The expected output of the array must be [float1 float2 float3 float4].

I did try this:

uint8_t data_array[80];

    float value1;
    float value2;
    float value3;
    float value4;


    uint8_t data0[20];
    uint8_t data1[20];
    uint8_t data2[20];
    uint8_t data3[20];

    ret_code_t err_code;

    err_code = nrfx_saadc_sample_convert(0, &sample);
    APP_ERROR_CHECK(err_code);

    value1 = sample * 3.0 / 4096;
    sprintf((char*)data0, "%.2f", val0);
    memcpy(&data_array[0], &val0, sizeof(val0));

    err_code = nrfx_saadc_sample_convert(1, &m_sample);
    APP_ERROR_CHECK(err_code);

    value2 = sample * 3.0 / 4096;
    sprintf((char*)data1, "%.2f", val1);
    memcpy(&data_array[20], &val1, sizeof(val1));

    err_code = nrfx_saadc_sample_convert(2, &m_sample);
    APP_ERROR_CHECK(err_code);

    value3 = sample * 3.0 / 4096;
    sprintf((char*)data2, "%.2f", val2);
    memcpy(&data_array[40], &val2, sizeof(val2));

    err_code = nrfx_saadc_sample_convert(3, &m_sample);
    APP_ERROR_CHECK(err_code);

    value4 = sample * 3.0 / 4096;
    sprintf((char*)data3, "%.2f", val3);
    memcpy(&data_array[60], &val3, sizeof(val3));
  

    sprintf(data_array, "%.2f %.2f %.2f %.2f ", val0, val1, val2, val3);
    uint16_t d_len = strlen(data_array);

    err_code = ble_nus_data_send(&m_nus, data_array, &d_len, m_conn_handle); 
    APP_ERROR_CHECK(err_code);

Because I didn't know how to put the floats into an uint8_t array I tried to make it a char. But as you see it is very messy. Can someone help me out?

【问题讨论】:

    标签: c


    【解决方案1】:

    You could send the float array as raw data, ie, the bytes they already are:

    float values[4];
    
    values[0] = sample * ...
    values[1] = sample * ...
    values[2] = sample * ...
    values[3] = sample * ...
    
    uint16_t d_len = sizeof(values);
    
    err_code = ble_nus_data_send(&m_nus, values, &d_len, m_conn_handle); 
    APP_ERROR_CHECK(err_code);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-06-13
      • 1970-01-01
      • 2012-04-07
      • 1970-01-01
      • 2018-09-16
      • 1970-01-01
      • 1970-01-01
      • 2020-05-29
      相关资源
      最近更新 更多