2017-08-11 78 views
-1

我在調試我的應用程序時遇到了一個錯誤,我已經能夠指出錯誤似乎發生在調用函數adc_gain_enum_to_real_gain(),但是我不明白爲什麼它會出錯,我懷疑涉及傳遞/讀取指針&adc_gain。任何提示?我的指針初始化不好嗎?

在此先感謝!

void saadc_handler_interrupt(nrf_drv_saadc_evt_t const * const p_event) 
{ 
    uint32_t err_code; 
    uint16_t voltage; 
    nrf_saadc_value_t adc_result; 
    uint16_t tmp_voltage; 
    float adc_gain; 

    if (p_event->type == NRF_DRV_SAADC_EVT_CALIBRATEDONE) 
    { 
     m_adc_cal_in_progress = false; 
    } 
    else if (p_event->type == NRF_DRV_SAADC_EVT_DONE) 
    { 
     adc_result = p_event->data.done.p_buffer[0]; 
     err_code = nrf_drv_saadc_buffer_convert(p_event->data.done.p_buffer, 1); 
     APP_ERROR_CHECK(err_code); 

     err_code = adc_gain_enum_to_real_gain(ADC_GAIN, &adc_gain); //<===HERE!! 
     APP_ERROR_CHECK(err_code); 

     float tmp = adc_result/(((1/6)/ADC_REFERENCE_VOLTAGE) * pow(2, ADC_RESOLUTION_BITS)); 
     tmp_voltage = (uint16_t) ((tmp/m_battery_divider_factor) * 1000); 
     voltage = ((tmp_voltage + 5)/10) * 10; // Round the value. 

     NRF_LOG_INFO("Read value from saadc %d\nV",voltage); 
     batt_event_handler_adc(voltage); 
    } 

    //nrf_drv_saadc_uninit(); 
} 

這樣的功能是

uint32_t adc_gain_enum_to_real_gain(nrf_saadc_gain_t gain_reg, float * const real_val) 
{ 
    switch(gain_reg) 
    { 
     case NRF_SAADC_GAIN1_6: *real_val = 1/(float)6; 
     break; 
     case NRF_SAADC_GAIN1_5: *real_val = 1/(float)5; 
     break; 
     case NRF_SAADC_GAIN1_4: *real_val = 1/(float)4; 
     break; 
     case NRF_SAADC_GAIN1_3: *real_val = 1/(float)3; 
     break; 
     case NRF_SAADC_GAIN1_2: *real_val = 1/(float)2; 
     break; 
     case NRF_SAADC_GAIN1: *real_val = 1; 
     break; 
     case NRF_SAADC_GAIN2: *real_val = 2; 
     break; 
     case NRF_SAADC_GAIN4: *real_val = 3; 
     break; 
     default: return M_BATT_STATUS_CODE_INVALID_PARAM; 
    }; 

    return M_BATT_STATUS_CODE_SUCCESS; 
} 
+1

請逐字引用錯誤消息,並確定它發生的行。 – Yunnosch

+1

[MCVE]請.. –

+0

你有什麼錯誤? –

回答

1

這裏

  float tmp = adc_result/(((1/6)/ADC_REFERENCE_VOLTAGE) * pow(2, ADC_RESOLUTION_BITS)); 

(1/6)將始終評估爲0。這是一個整數部分!

因此,整個表達式(((1/6)/ADC_REFERENCE_VOLTAGE) * pow(2, ADC_RESOLUTION_BITS))結果爲0.(注意:這裏是浮點數),這又在這裏引起一個除零的結果adc_result/...

爲了解決這個問題無論是做

(1./6) 

(1/6.) 

((float) 1/6) 

(1 /(float) 6) 

或上述的任何組合。


無關,但對整數除法以及相關的麻煩另一個原因是在這裏:

(tmp_voltage + 5)/10 

修復如上。