C语言数组和for循环不能正常工作

标签 c embedded pic

我正在使用 PIC18F26K83 并尝试使用 NTCALUG02A103F 测量温度。我已经计算出 ADC 输出和它们所对应的温度。我创建了 2 个数组:1 个用于 ADC 值,1 个用于该 ADC 值的温度。在 for 循环中,我比较来自 ADC 的值和来自数组的值,如果我的 ADC 值小于数组值,它会不断递减数组元素,最终它将以 258 ADC 值结束,这是我数组的最后一个元素。但是,在 for 循环中它永远不会递减。即使我的 ADC 值为 2000,它也不会继续。它卡在 i=32 处。这是代码:

int i;
int temperature;
int temp_data;
int temp_ADC_array[34] = {259,  293,  332,  377,  428,  487,  555,  632,  720,
                          821,  934,  1062, 1203, 1360, 1531, 1715, 1910, 2113,
                          2320, 2528, 2731, 2926, 3108, 3274, 3422, 3552, 3663,
                          3756, 3833, 3895, 3945, 3983, 4013, 4036};
int temp_array[34] = {125, 120, 115, 110, 105, 100, 95,  90,  85,  80, 75, 70,
                      65,  60,  55,  50,  45,  40,  35,  30,  25,  20, 15, 10,
                      5,   0,   -5,  -10, -15, -20, -25, -30, -35, -40};
void main() {
  while (1) {
    temp_data = ADC_READ(3);
    for (i = 33; temp_data < temp_ADC_array[i]; i--) {
      temperature = temp_array[i];
    }
  }

编辑:这个 for 循环也不起作用:

for (i = 0; i < 34; i++) {
  if (temp_data > temp_ADC_array[33 - i]) {
    temperature = temp_array[33 - i];
    break;
  }
}

编辑 2:我用 LED 测试它,我的电路上没有 USB,所以我不能使用调试器。这是我测试温度的方法:(我检查 LED 的闪烁情况)

for(i; temperature>=0; temperature=temperature-10){
  led=1;
  delay_ms(1000);
  led=0;
  delay_ms(1000);
}   
delay_ms(5000);

最佳答案

这个答案只是重复我的评论。它的目的是让人们可以接受它作为答案,以便人们立即看到这个问题已得到解决。


I think your first loop might be stopping before temparature is assigned when the condition is no longer true. That means that temperature would have the value one too early. The second loop looks fine to me though

第一个循环是

void main() {
  while (1) {
    temp_data = ADC_READ(3);
    for (i = 33; temp_data < temp_ADC_array[i]; i--) {
      temperature = temp_array[i];
    }
  }

它的问题是一旦条件 temp_data < temp_ADC_array[i] 停止循环。不再满足。所以如果这发生在 i==0 , 温度仍为 temp_array[1] .

第二个循环是

for (i = 0; i < 34; i++) {
  if (temp_data > temp_ADC_array[33 - i]) {
    temperature = temp_array[33 - i];
    break;
  }
}

它应该可以工作,因为它只会在 分配正确的温度后中断。

关于C语言数组和for循环不能正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57357428/

相关文章:

c - PIC C - 通过 USB 发送 200 个值,但它只发送其中的 25 个左右

C 宏扩展命令

c - c语言中如何比较字符串

c - XC32 从 1.32 迁移到 1.34

c - 如何计算#define 中的逗号

c - PIC单片机如何添加两个超声波传感器

python - 如何使用 SWIG 根据 C 函数返回类型返回特定异常?

c - 身份属性的位操作

c++ - 如何在启动时隐藏鼠标指针?

c - C 中的结构体与数组问题