我正在用C编写代码,读取温度并将其发送到用GTK3制作的GUI。
这是代码:
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <stdio.h>
char Vo[10]; // voltage out
float Ro, R1 = 6247; // value of resistance at 20C in the thermistor
float T0 = 298.15; // 25 degrees C in Kelvin
float logR2, R2, T;
float A = 1.281426510e-03, B = 2.368116050e-04, C = 0.9002008458e-07; // Steinhart-Hart and Hart Coefficients
char *senseTemp() {
FILE *fp;
char command[50];
int c;
//get the Analog value
fp = fopen("/sys/bus/iio/devices/iio:device0/in_voltage0_raw", "r");
if (fp == NULL) {
perror("Error: ");
return (1);
}
int i = 0;
while (1) {
c = fgetc(fp);
if (feof(fp)) {
break;
}
printf("%c ", c);
if (c != EOF) {
Vo[i] = c;
++i;
}
}
fclose(fp);
//printf("Analog Reading: %sn", Vo);
//convert the value to resistance
int V = 0;
float Vout = 0;
V = atoi(Vo); //TO convert an array to an integer
//printf("Value of V: %dn", V);
Vout = V * (1.8 / 4095.0); //Voltage out of the thermistor
//printf("Voltage out from thermistor: %fn", Vout);
R2 = R1 * ((1.8 / Vout) - 1);
logR2 = log(R2);
T = (1.0 / (A + B * logR2 + C * logR2 * logR2 * logR2)); // Steinhart and Hart Equation. T = 1 / {A + B[ln(R)] + C[ln(R)]^3}
T = T - 273.15;
char Tfinal[10];
i = 0;
snprintf(Tfinal, 10, "%.0f", T);
printf("Here is the value: %sn", Tfinal);
return Tfinal;
}
如果我使用return Vo;
,这些值会正确地返回到GUI,我可以看到它们,但我想将这些值转换为摄氏度,这就是变量T所包含的。但是在GUI中显示温度的gtk_label_set_text()
只需要一个指向字符串的指针。
因此,在我的代码中,如果我使用return Vo
,它可以工作,但不适用于return Tfinal
。
return Tfinal;
具有未定义的行为,因为您使用本地自动存储返回数组的地址。此数组在函数返回时被丢弃。为数组分配malloc()
以将其返回给调用者。
Tfinal
是函数的本地数组。这意味着当您使用return Tfinal;
时,您将返回一个指向数组第一个元素的指针。因此,您将返回一个指向其生命周期已结束的变量的指针。取消引用这样的指针(甚至读取它(会调用未定义的行为。相反,Vo
是在文件范围内定义的,因此具有完整的程序生存期。
您需要动态分配内存并返回该内存(当您使用完它时,free
是内存(,声明数组static
,使其生存期为整个程序的生存期,或者将定义移动到文件范围。