我正在与Segger adc,nRF52832 DK和hx711 embedded studio一起工作。问题是,我想复制一个局部变量,将最新的ADC值存储到hx711回调函数中的全局变量,然后读取这个全局变量。当我在回调函数中读取这个值时,一切都是正常的。全局变量和局部变量是相同的。但是当我在main()的开头读取这个全局变量时,全局变量总是等于0。请看附件中的代码。谢谢
#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
}
/**
* @}
*/发布于 2019-12-30 03:26:32
更改hx_test_val的定义以包括volatile限定符:
volatile int hx_test_val;我怀疑编译器的印象是hx_test_val的值不可能改变,因为编译器知道的任何东西都不可能接触到hx_test_val -在代码中没有对回调函数的直接调用,所以编译器认为它只能在您访问main中的hx_test_val时返回一个常量值0。
https://stackoverflow.com/questions/59522525
复制相似问题