1

I am working with hx711 adc, nRF52832 DK, and Segger embedded studio. The problem is, that I want to do a copy of local variable that stores latest adc value to global variable in hx711 callback function and then read this global variable. Everything is OK when I read this value inside the callback function. Global variable and local are the same. But when I read this global variable in the beginning of main(), global variable always equals 0. Please see the attached code. thanks

    #include "hx711.h"
    #include "nrf_delay.h"

    #include "nrf_log.h"
    #include "nrf_log_ctrl.h"
    #include "nrf_log_default_backends.h"


    int hx_test_val;



void hx711_callback(hx711_evt_t evt, int value) // hx711 runs on continous sampling mode, so this function is called on rate 10 or 80Hz, depending on hardware design
{
   hx_test_val = value; // local value is copied to global variable hx_test_val

   if(evt == DATA_READY)
    {
      NRF_LOG_INFO("ADC measuremement %d", hx_test_val); // here, the global variable is equal to local variable "value" (input of hx711_callback())
    }
   else
    {
      NRF_LOG_INFO("ADC readout error. %d 0x%x", value, hx_test_val);
    }
}


    /**@brief Function for initializing the nrf log module.
     */
static void log_init(void)
{
   ret_code_t err_code = NRF_LOG_INIT(NULL);
   APP_ERROR_CHECK(err_code);

   NRF_LOG_DEFAULT_BACKENDS_INIT();
}



    /**@brief Application main function.
     */
int main(void)
{

   hx711_init(INPUT_CH_A_128, hx711_callback);
   log_init();

/* Start continous sampling. Sampling rate is either
10Hz or 80 Hz, depending on hx711 HW configuration*/
   hx711_start(false);
   nrf_delay_ms(50);

   NRF_LOG_INFO("hx_copy: %d",hx_test_val); // here, the global variable is equal to 0

 }


    /**
     * @}
     */
  • It will be set after the (first) callback call. I can't see that you are calling thie callback strictly, and there is no info about that where it will be called. – VillageTech Dec 29 '19 at 19:27
  • Global variables are initialized to 0. If `hx711_callback` is not run, `hx_test_val` will not be changed. From your code I assume that the log message is outputted before any callback. – flowit Dec 29 '19 at 19:27

1 Answers1

4

Change the definition of hx_test_val to include the volatile qualifier:

volatile int hx_test_val;

I suspect that the compiler is under the impression that the value of hx_test_val cannot have changed because nothing that the compiler knows about could have touched hx_test_val - there are no direct calls to your callback function in your code, so the compiler believes it can just return a constant value of 0 at the point you access hx_test_val in main.