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

C language array & for loop does not work properly

我正在使用 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;
  }
}

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

您读取数组之外的内容,进入项目 [-1] 等等,因为如果您读取的值低于 259,循环将永远不会停止。

循环应该是这样写的

for(i=0; i<SIZE; i++) 
{ 
  if(temp_data < temp_ADC_array[SIZE-1-i]) 
  { 
    found = true; 
    break;
  }
}

但是你也可以忘记这一点,因为你有一个排序的查找 table,因此应该改用二分查找。它可能会大大加快一切,特别是因为 16 位比较不是 PIC 的强项。

如果使用 "O log(n)",最坏情况下您将得到 5-6 次比较,而不是 34 次比较。尽管二分搜索意味着一些指针杂耍开销,但它仍然应该大大优于线性搜索。这对于如此缓慢的 CPU 非常重要,特别是因为与 ADC 相关的代码往往对性能至关重要。