单行代码的Arduino运行时间

bem*_*e24 0 c++ arduino

Arduino 运行一行代码需要多长时间?或者从模拟引脚读取模拟值?

我试过这段代码来读取模拟读取时间:

void setup() {
  Serial.begin(9600);
  t1 = micros();
  val = analogRead(pin);
  t2 = micros();
  Serial.print(t2-t1);
}
Run Code Online (Sandbox Code Playgroud)

它打印 208 微秒,但我在表单源中读到的内容是,读取模拟输入需要 100 微秒。我的代码有问题吗?

这段代码读取一行代码的执行时间:

void setup() {
  Serial.begin(9600);
  t1 = micros();
  int x = 1 + 2;
  t2 = micros();
  Serial.print(t2-t1);
}
Run Code Online (Sandbox Code Playgroud)

这显示 0 微秒。这里发生了什么?我究竟做错了什么?

Mor*_*oth 5

一行 Arduino 代码没有固定的执行时间。

delay(1000);运行大约需要一秒钟,而运行Serial.print("Hello, World!");可能需要几百微秒。

这取决于线路的作用。一行 Arduino 代码可能会转换为 1 行或多行汇编代码。

Arduino 代码中的一个简单 for 循环:

for (i=0; i<100; i++) {
    p[i] = i;
}
Run Code Online (Sandbox Code Playgroud)

在汇编代码中可能会变成这样:

LDI     R19,0x00
MOVW    R30,R24
ST      Z+,R19
SUBI    R19,0xFF
CPI     R19,0x64
BRCS    PC-0x03
Run Code Online (Sandbox Code Playgroud)

这也不能解决您的问题,因为汇编代码行不一定具有相同的执行时间。

您唯一能做的就是为您感兴趣的部分计时。

要回答您列出的具体示例:

示例 1

void setup() {
  Serial.begin(9600);
  t1 = micros();
  val = analogRead(pin);
  t2 = micros();
  Serial.print(t2-t1);
}
Run Code Online (Sandbox Code Playgroud)

的速度val = analogRead(pin)由几个因素决定。将值存储到寄存器 ( val =) 将需要 1 个指令周期。analogRead(pin)PIN缓冲区读取模拟值 ( )需要一些指令。

示例 2

void setup() {
  Serial.begin(9600);
  t1 = micros();
  int x = 1 + 2;
  t2 = micros();
  Serial.print(t2-t1);
}
Run Code Online (Sandbox Code Playgroud)

int x = 1 + 2;执行需要 0 微秒的原因是编译器优化了您编写的代码。由于变量x从未在其作用域中使用过,编译器只是删除了这一行。这意味着该行不在 Arduino 上,因此不会执行。所以你实际上在做的是:

void setup() {
  Serial.begin(9600);
  t1 = micros();
  t2 = micros();
  Serial.print(t2-t1);
}
Run Code Online (Sandbox Code Playgroud)

即使它没有删除该行,添加常量,即1 + 2会被优化为3,在 Arduino 上永远不会发生加法操作。