我正在为一些温度感应编程PIC。最终输出通过UART发送到PC。温度传感器ID的MSB用于确定传感器的位置。
我刚刚添加了我使用过的代码中的一小部分内容(其他代码没有任何意义)。问题在于我使用的位置[]字符。我已经尝试了几种方法(* location,location [7]),但大多数都无法编译。下面的方法可以编译,但在" Location ="之后%s中没有显示任何内容。我也试过%c,但仍然没有显示任何内容。
void convert_1820_send_temp(int *buff)
{
// have removed other variables
char location[];
// Determine location based on sensor id
if (dev_adr[7] == 181)
{
strcpy(location, "outside");
}
if (dev_adr[7] == 30)
{
strcpy(location, "ceiling");
}
if (dev_adr[7] == 46)
{
strcpy(location, "under ");
}
if (dev_adr[7] == 18)
{
strcpy(location, "inside ");
}
else
{
strcpy(location, "unknown");
}
sprintf(s,
"Temp=%c%d.%d degrees C, sensor=\"%d %d %d %d %d %d %d %d\",Location=%s\r\n",
negSign, tempWhole, decimal, dev_adr[7], dev_adr[6], dev_adr[5],
dev_adr[4], dev_adr[3], dev_adr[2], dev_adr[1], dev_adr[0]), location;
USARTWriteString(s);
}
任何帮助都会非常感谢。
答案 0 :(得分:3)
您需要在括号内移动,location
。
答案 1 :(得分:2)
在您的示例中,您尝试将数据放入没有分配空间的数组中。
相反,请使用以下内容。 (我还将if
语句重构为switch
)。该位置是一个指针,指向您想要的字符串。这比使用strcpy
复制字符更安全,更有效。
char const *location;
switch (dev_addr[7]) {
case 181:
location = "outside";
break;
case 30:
location = "ceiling";
break;
default:
location = "unknown";
break;
}
答案 2 :(得分:1)
你有什么不应该编译...试试这个:
void convert_1820_send_temp(int *buff)
{
// have removed other variables
char location[8]; // Minimum of 8 for 7 char strings below
char s[512];
// Determine location based on sensor id
switch( dev_adr[7] ) {
case 181:
strcpy(location, "outside");
break;
case 30:
strcpy(location, "ceiling");
break;
case 46:
strcpy(location, "under ");
break
case 18:
strcpy(location, "inside ");
break;
default:
strcpy(location, "unknown");
break;
}
sprintf(s, "Temp=%c%d.%d degrees C, sensor=\"%d %d %d %d %d %d %d %d,Location=\"%s\"\r\n",
negSign, tempWhole, decimal, dev_adr[7], dev_adr[6], dev_adr[5],
dev_adr[4], dev_adr[3], dev_adr[2], dev_adr[1], dev_adr[0], location );
USARTWriteString(s);
}