Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/c/63.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C 比较赢得的价值';我不能毫不拖延地工作_C_Embedded - Fatal编程技术网

C 比较赢得的价值';我不能毫不拖延地工作

C 比较赢得的价值';我不能毫不拖延地工作,c,embedded,C,Embedded,我正在编写一个应用程序,它将为我们的产品计时鼠标延迟 它的工作方式是,它发送鼠标移动,并测量从那时起到屏幕上出现像素变化之间的时间 为什么延迟会影响程序 int check_for_pixel_change() { // Gets the pixels R value unsigned char value = *((unsigned char *) (0x100)); // If this delay is not here then the loop will a

我正在编写一个应用程序,它将为我们的产品计时鼠标延迟

它的工作方式是,它发送鼠标移动,并测量从那时起到屏幕上出现像素变化之间的时间

为什么延迟会影响程序

int check_for_pixel_change() {

    // Gets the pixels R value
    unsigned char value = *((unsigned char *) (0x100));

    // If this delay is not here then the loop will always return 1
    usleep(5);

    if(value == (0x80)) return 0;
    else return 1;
}

int main() {
    // Send move / start timer

    while(check_for_pixel_change());

    // stop timer
    return 0;
}

下面是有效的代码

感谢@barak manos&&@santosh-a

我需要将char更改为volatile,因为它会被不同的程序不断更改

int check_for_pixel_change() {

    // Gets the pixels R value
    volatile unsigned char value = *(volatile unsigned char *) (0x100);

    if(value == (0x80)) return 0;
    else return 1;
}

int main() {
    // Send move / start timer

    while(check_for_pixel_change());

    // stop timer
    return 0;
}

旁注:您可以将整个代码简化为
while(*(unsigned char*)0x100!=0x80)。假设您在后台有某种调度程序(OS),那么
usleep
可能允许其他线程完成其工作,并在该地址设置
0x80
。如果是ISR(而不是线程),那么肯定还有其他原因,因为ISR的优先级始终高于系统中的任何其他线程。请将
无符号字符值
更改为
易失性无符号字符值
,然后进行检查。事实上
易失性
解决了问题,这意味着问题是编译器优化的结果(因此我推测是并发的)(多线程)问题是错误的)。您应该阅读并理解
volatile
,而不仅仅是在有人告诉您的情况下使用它!(尽管他实际上是对的)。全局变量不在函数范围内也是一种很好的做法,因此它本身是清晰可见的。有人发布答案-这不是注释的目的。