c - C中的延迟函数不延迟

标签 c keil

这是一个非常奇怪的问题,因为它应该可以工作,但事实并非如此。 我的任务是做一个延迟程序的简单函数。

所以time before use a function

使用函数后: time after using 我想要 1 秒的延迟,所以我增加了 100000 次(100 之前)的迭代次数,但时间没有改变。 after increasing iteration

为什么?按逻辑,如果我增加迭代次数,时间应该会更长......

编辑:

#include <LPC21xx.H>

void Delay(){
    long int i;
    for(i=0; i<48000000000;i++){
    }
}

int main(){
    //set pin 16 P1 as out
    IO1DIR = 0x10000;
    //set pin 16  P1 on 1
    IO1SET = 0x10000;
    Delay();
    //set pin 16 port P1 on 0
    IO1CLR = 0x10000;

}

我使用 uVision Keil。

最佳答案

使用 nop () 函数将许多 NO-OP 指令插入到您的 C 代码中。计算出目标上单个 NOP 所需的时间,并根据需要使用尽可能多的时间。来源:keil.com/support/docs/606.htm

对于这个“样本”,您可以尝试使用 Delay(1000) 更改该值;

#include <LPC21xx.H>
#include <intrins.h>

#pragma O0
void Delay(volatile uint32_t cnt) {
    while(cnt--)
        _nop_();
}

void DelayWithoutNop(volatile uint32_t cnt) {
    while(cnt--);
}


int main(){
    //set pin 16 P1 as out
    IO1DIR = 0x10000;
    //set pin 16  P1 on 1
    IO1SET = 0x10000;
    Delay(1000);
    DelayWithotNop(3000);
    //set pin 16 port P1 on 0
    IO1CLR = 0x10000;

}

关于c - C中的延迟函数不延迟,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54933109/

相关文章:

c - math.h 与文件的链接

c - 是否保证执行 memcpy(0,0,0) 是安全的?

stm32 - 无法让STM32F103RB usart1与hc-05通信

c - 获取错误符号 current_process 多重定义,对错误含义以及如何修复感到困惑?

c++ - push_back() 导致程序在进入 main() 之前停止

c - 如何关闭来自 gcc 的错误浮点/长错误消息

c - 将ASM转换为C

c - 如何释放动态分配数组中的内存?

c++ - 与arm微 Controller 的串行通信

c++ - 为什么我会收到命名空间标识符错误?