目前共有35篇帖子。
【單片機實際應用】開機時在MySQL數據庫中自動記錄開機時間和室內溫度(由DS18B20通過串口提供)
21樓 巨大八爪鱼 2015-6-28 11:51
[conn.h]
#define SERVER_NAME "localhost"
#define DB_USER "root"
#define DB_PASSWD "YOUR_PASSWORD"
#define DB_NAME "server"
22樓 巨大八爪鱼 2015-6-28 11:52
[logview.c]
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <mysql.h>
#include "conn.h"

int main(int argc, char* argv[])
{
    MYSQL conn;
    mysql_init(&conn);
    if (!mysql_real_connect(&conn, SERVER_NAME, DB_USER, DB_PASSWD, DB_NAME, 0, NULL, 0))
    {
        printf("Cannot connect to the database server.\n");
        return 1;
    }
    mysql_query(&conn, "SET NAMES utf8");
   
    printf("Powerlog Version 2.2\n");
    FILE* file = fopen("powerlog.txt", "w");
    char title[] = "ID\tTIME\n";
    printf(title);
    fwrite(title, strlen(title), 1, file);
   
    char sql[] = "SELECT LogID, LogTime FROM PowerLog WHERE LogFlag = 'POWER ON' AND ComputerIP = '192.168.0.4' ORDER BY LogTime DESC";
    mysql_query(&conn, sql);
    MYSQL_RES* rs = mysql_store_result(&conn);
    MYSQL_ROW row;
    char line[100];
    unsigned int i;
    for (i = 0; row = mysql_fetch_row(rs); i++)
    {
        int id = atoi(row[0]);
        char timestr[50];
        sprintf(timestr, "%s", row[1]);
       
        sprintf(line, "%d\t%s\n", id, timestr);
        if (i < 20)
            printf(line);
        fwrite(line, strlen(line), 1, file);
    }
   
    fclose(file);
    mysql_free_result(rs);
    mysql_close(&conn);
    return 0;
}
23樓 巨大八爪鱼 2015-6-28 11:52
[Makefile]
MYSQL=-I/usr/include/mysql -L/usr/lib64/mysql -lmysqlclient

powerlog2: powerlog2.o logview.o
    gcc powerlog2.o temperature.o UART.o -o powerlog2 $(MYSQL)
    gcc logview.o -o logview $(MYSQL)

powerlog2.o: powerlog2.c conn.h temperature.o UART.o
    gcc -c powerlog2.c $(MYSQL)
   
temperature.o: temperature.c temperature.h
    gcc -c temperature.c

UART.o: UART.c UART.h
    gcc -c UART.c

logview.o: logview.c conn.h
    gcc -c logview.c $(MYSQL)
   
clean:
    rm powerlog2 *.o

24樓 巨大八爪鱼 2015-6-28 11:53
[powerlog2.c]
//Version: 2.2
#include <stdio.h>
#include <string.h>
#include <mysql.h>
#include <unistd.h>
#include "conn.h"
#include "temperature.h"
#include "UART.h"

int main(int argc, char* argv[])
{
    char uartopened = 1;
    if (UART_Open() == 0)
        uartopened = 0;
   
    MYSQL conn;
    mysql_init(&conn);
    if (!mysql_real_connect(&conn, SERVER_NAME, DB_USER, DB_PASSWD, DB_NAME, 0, NULL, 0))
    {
        printf("Cannot connect to the database server.\n");
        return 1;
    }
    mysql_query(&conn, "SET NAMES utf8");
   
    printf("Powerlog Version 2.2\n");
    printf("Welcome\n");
   
    char sql[200];
    memset(sql, 0, sizeof(char) * 200);
    char sql2[100]; // the Backup Query, which is executed when the main sql is corrupted
    memset(sql2, 0, sizeof(char) * 100);
    char temp[8];
    int i = 10;
    float f;
    if (argc >= 2 && strcmp(argv[1], "on") == 0)
    {
        strcat(sql, "INSERT INTO PowerLog (LogTime, LogFlag, Temperature) VALUES (NOW(), 'POWER ON', TRIM('");
        strcat(sql2, "INSERT INTO PowerLog (LogTime, LogFlag, Temperature) VALUES (NOW(), 'POWER ON', 'Query Error')");
    }
    else
    {
        // only for development
        strcat(sql, "INSERT INTO PowerLog (LogTime, Temperature) VALUES (NOW(), TRIM('");
        strcat(sql2, "INSERT INTO PowerLog (LogTime, Temperature) VALUES (NOW(), 'Query Error')");
    }
    if (uartopened == 1)
    {
        get_temperature(&f); // avoid the first possible error value
        while (i--)
        {
            usleep(10000);
            get_temperature(&f);
            tempstr(&f, temp);
            strcat(sql, temp);
        }
    }
    else
        strcat(sql, "UART Unavailable");
    strcat(sql, "'))");
    int result = mysql_query(&conn, sql);
    if (result == 1)
        mysql_query(&conn, sql2);
   
    //Display the time
    mysql_query(&conn, "SELECT now()");
    MYSQL_RES* rs = mysql_store_result(&conn);
    MYSQL_ROW row = mysql_fetch_row(rs);
    char buffer[100];
    sprintf(buffer, "%s", row[0]);
    printf("MySQL Time: %s\n", buffer);
    mysql_free_result(rs);
   
    mysql_close(&conn);
    if (uartopened == 1)
        USART_Close();
    return 0;
}

25樓 巨大八爪鱼 2015-6-28 11:53
[temperature.c]
#include <stdio.h>
#include <unistd.h>
#include "UART.h"

#define DSNEG 4
#define DSERR 6

#define BIT(n) 1<<n

char buffer[513];

void get_temperature(float* temp)
{
    UART_Send(0x83);
    usleep(100000);
    UART_Receive(buffer);
    if (buffer[1] & BIT(DSERR))
        *temp = -999.99;
    else
    {
        *temp = buffer[2] * 1.00 + buffer[3] * 0.01;
        if (buffer[1] & BIT(DSNEG))
            *temp = -*temp;
    }
}

void tempstr(float* temp, char* str)
{
    sprintf(str, "%.2f℃\t", *temp);
}

26樓 巨大八爪鱼 2015-6-28 11:53
[temperature.h]
void get_temperature(float* temp);
void tempstr(float* temp, char* str);
27樓 巨大八爪鱼 2015-6-28 11:53
[UART.c]
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h> // UNIX Standard Function Definitions
#include <fcntl.h> // File Control Definitions
#include <errno.h> // File Control Definitions
#include <termios.h> // POSIX Terminal Control Definitions
#include "UART.h"

struct termios tty;
struct termios tty_old;
int UART_id = 0;

int UART_Open(void)
{
    memset(&tty, 0, sizeof(tty));
    UART_id = open(UART_PORT, O_RDWR | O_NOCTTY | O_NDELAY);
    if (UART_id < 0)
    {
        printf("Warning: Cannot open the serial port!\n");
        return 0;
    }
   
    /* Error Handling */
    if (tcgetattr(UART_id, &tty) != 0)
    {
        printf("Error: %d from tcgetattr: %s \n", errno,strerror(errno));
        return 0;
    }
   
    /* Save old tty parameters */
    tty_old = tty;
   
    /* Set Baud Rate */
    cfsetospeed(&tty, (speed_t)B9600);
    cfsetispeed(&tty, (speed_t)B9600);
   
    /* Setting other Port Stuff */
    tty.c_cflag &= ~PARENB; // Make 8n1
    tty.c_cflag &= ~CSTOPB;
    tty.c_cflag &= ~CSIZE;
    tty.c_cflag |= CS8;
   
    tty.c_cflag &= ~CRTSCTS; // no flow control
    tty.c_cc[VMIN] = 1; // read doesn't block
    tty.c_cc[VTIME] = 5; // 0.5 second read timeout
    tty.c_cflag |= CREAD | CLOCAL; // turn on READ & ignore ctrl lines
   
    /* Make raw */
    cfmakeraw(&tty);
   
    /* Flush Port, then applies attributes */
    tcflush(UART_id, TCIFLUSH);
    if (tcsetattr(UART_id, TCSANOW, &tty) != 0)
    {
        printf("Error: %d from tcgetattr \n", errno);
        return 0;
    }
   
    return UART_id;
}

void UART_Send(unsigned char Byte)
{
    write(UART_id, &Byte, 1);
    // It was definitely not necessary to write byte per byte, also int n_written = write( UART_id, cmd, sizeof(cmd) -1) worked fine.
}

int UART_Receive(char* buf)
{
    int len = read(UART_id, buf, 512);
    buf[len] = '\0';
    return len;
}

void USART_Close()
{
    close(UART_id);
}


28樓 巨大八爪鱼 2015-6-28 11:53
[UART.h]
#define UART_PORT "/dev/ttyUSB0"

int UART_Open(void);
void UART_Send(unsigned char Byte);
int UART_Receive(char* buf);
void USART_Close();

29樓 巨大八爪鱼 2015-6-28 11:54
單片機端程序完畢
30樓 巨大八爪鱼 2015-6-30 09:59
補充:PHP讀取DS18B20溫度值的示例程序
<?php
define("DSNEG", 4);
define("DSERR", 6);
function BIT($n) {
    return 1 << $n;
}
function decodeTemperature($flags, $TN, $TD) {
    if ($flags & BIT(DSERR)) {
        $value = "Error";
    } else {
        $value = $TN * 1.00 + $TD * 0.01;
        if ($flags & BIT(DSNEG)) {
            $value = -$value;
        }
    }
    return $value;
}

$filename = "/dev/ttyUSB0";
$fp = fopen($filename, "a+");
fwrite($fp, "\x83");
$flag = fread($fp, 1);
$data = fread($fp, 3);
printf("<b>Flag:</b> 0x%x (Useless)<br>\n", $flag);
printf("<b>Data:</b> 0x%x, 0x%x, 0x%x<br>\n", ord($data{0}), ord($data{1}), ord($data{2}));
$temperature = decodeTemperature(ord($data{0}), ord($data{1}), ord($data{2}));
echo "<b>Temperature:</b> $temperature&deg;C";
fclose($fp);
?>

輸出:
Flag: 0x0 (Useless)
Data: 0xaf, 0x1b, 0x25
Temperature: 27.37°C

回復帖子

內容:
用戶名: 您目前是匿名發表
驗證碼:
 
 
©2010-2024 Arslanbar [手機版] [桌面版]
除非另有聲明,本站採用創用CC姓名標示-相同方式分享 3.0 Unported許可協議進行許可。