将char和float值传递给字符串

时间:2018-10-02 15:39:46

标签: c pic

我需要使用字符串发送get请求,因此需要将浮点数和char值传递给字符串才能发送它。我试图使用ESP8266模块将PIC18F4550连接到wifi,我也需要读取和写入数据库。我一直在使用此功能来发送AT指令,并且该功能运行良好:

void send (char dato[]){
    int i = 0;
    while (dato[i]!=0){
        TXREG=dato[i];
        i++;
        while(TRMT==0);
    }
    TXREG = 0x0D; 
    while(TRMT==0);
    TXREG = 0x0A;
}

我的问题是我需要发送:

send("GET /ESPic/index3.php?temp=temp&luz=luz");

但是luz是char并且temp是float。使用FTDI232和Arduino IDE我正在读取PIC和ESP8266之间的数据,我真的不知道该怎么做。

2 个答案:

答案 0 :(得分:3)

您的平台支持sprintf的Assumimg,您可能需要这样做:

float temp;
char luz;
...
char buffer[200];
sprintf(buffer, "GET /ESPic/index3.php?temp=%f&luz=%c", temp, luz);
send(buffer);

答案 1 :(得分:1)

首先将float转换为 string


发送float的文本版本时,最好避免使用"%f",并以足够的精度使用"%e""%g""%a"

"%f"对于很大的数字可能会很长。对于所有"0.000000"的大约一半(较小的),它都掩盖了无信息的+/- float

这3种格式e,g,a可以更好地控制最大长度,更容易确保使用所需的精度。

float temp;
char luz;
// send("GET /ESPic/index3.php?temp=temp&luz=luz");

#define SEND_FC_FMT "GET /ESPic/index3.php?temp=%.*e&luz=%c"
//                     -   d   .    ddd...ddd            e   - d...d \0 
#define FLT_ESTR_SIZE (1 + 1 + 1 + (FLT_DECIMAL_DIG-1) + 1 + 1 + 5 + 1)
char buffer[sizeof SEND_FC_FMT + FLT_ESTR_SIZE];

sprintf(buffer, SEND_FC_FMT, FLT_DECIMAL_DIG-1, temp, luz);
send (buffer);
相关问题