You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

添加if条件后Arduino变量值异常跳变的原因咨询

串口计数异常原因分析

这段代码在未添加if语句时,能正常从1开始递增并在串口监视器输出数值,但添加if语句后出现了截图中的异常计数情况,原因如下:

#include <Arduino_MKRIoTCarrier.h>
MKRIoTCarrier carrier;
int a;
int r,g,b;


void setup() {
    // put your setup code here, to run once:
    Serial.begin(9600);
    // Initialize serial and wait for port to open:
    Serial.begin(9600);
    // This delay gives the chance to wait for a Serial Monitor without blocking if none is found
    delay(1500); 
    carrier.begin();
    carrier.display.setRotation(0);
    a = 1;
}

void loop() 
{
    // put your main code here, to run repeatedly:
    Serial.println(a);
    a = a + 1;

    if (a = 10)
    {
        carrier.leds.setPixelColor(0, 255, 0, 0);
        carrier.leds.show();
    }
}

异常计数截图

问题根源

你在if条件里误用了赋值运算符=,而非判断相等的比较运算符==:

  • if (a = 10)会直接把10赋值给变量a,且这个赋值表达式的返回值为10(C++中非零值会被判定为true),因此每次进入loop都会执行if块内的代码。
  • 具体执行流程:每次loop先打印当前a的值,a自增1,接着if语句把a强制设回10,导致下一次循环打印的还是10,陷入死循环,所以串口输出一直停在10。

修复方法

把if条件里的=改成==,即:

if (a == 10)

这样才是判断变量a是否等于10的正确逻辑,代码就能恢复正常的递增计数。

内容的提问来源于stack exchange,提问作者Max

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.14 07:50:29