我想把arduino的温度数据保存到mysql数据库中。Arduino与MySQL数据库通过USB串行端口连接。为了将数据从Arduino保存到MySQL,我通过读取Arduino串行端口使用C编程语言。问题是,数据存储在mysql中,与监视器序列arduino上显示的数据不同。
串行监视器中来自Arduino的数据是:

26.37
26.27
26.38
26.50
...

从C中的串行端口读取的程序有:
    char TempChar;
    DWORD NoBytesRead;

    char query[100];
    char INSERT_DATA[] = "INSERT INTO lm35 (id, temp) VALUES (%d,%f)";
do{
    ReadFile(hComm,&TempChar,sizeof(TempChar),&NoBytesRead,NULL);
    sprintf(query, INSERT_DATA, 00, (float)TempChar);

     if (mysql_query(conn,query))
      {
       printf(" Error: %s\n", mysql_error(conn));
       return 0;
    }

      printf("OK \n");
}while(!kbhit());

 CloseHandle(hComm);
 mysql_close(conn);

mysql中表中的字段和数据类型是:
+-------+---------+------+-----+---------+----------------+
| Field | Type    | Null | Key | Default | Extra          |
+-------+---------+------+-----+---------+----------------+
| id    | int(11) | NO   | PRI | NULL    | auto_increment |
| temp  | float   | YES  |     | NULL    |                |
+-------+---------+------+-----+---------+----------------+

存储在mysql数据库表中的数据是:
+------+------+
| id   | temp |
+------+------+
| 1500 |   50 |
| 1499 |   10 |
| 1498 |   13 |
| 1497 |   56 |
| 1496 |   56 |
+------+------+

如何将temp(termperature)数据保存到mysql数据库中?为什么Arduino串行监视器上的温度数据和MySQL上的不一样?

最佳答案

不能在字符缓冲区上使用(float)强制转换,需要使用类似atof的命令:

sprintf(query, INSERT_DATA, 00, atof(TempChar));

您得到的是数字的ASCII值,比如'2'50'8'561013分别是换行符和回车符。在等待CRLF终止符时,您需要读入的不仅仅是一个字符,而是一系列字符。
您可能需要使用类似于fgets()的内容,而不是抓取单个字符,或者如果需要,则需要为数字创建缓冲区。你想阅读每一行文字,如果你能摆动它,就不想读单个字符。
注意由于id是自动递增的,所以不要在INSERT语句中指定它,只需省略该列和相关的值。MySQL将自动填充它。

10-04 10:57
查看更多