目前共有3篇帖子。 內容轉換:不轉換▼
 
點擊 回復
348 2
串口传入的温度数据分次读取程序
一派護法 十九級
1樓 發表于:2017-2-6 16:33
#include <fcntl.h>
#include <stdio.h>
#include <string.h>
#include <termios.h>
#include <unistd.h>

#define DSNEG (1 << 4)
#define DSERR (1 << 6)

char *getcode(unsigned char data)
{
    const char *list = "0123456789abcdef";
    static char code[5];
    strcpy(code, "0x??");
    code[2] = list[data >> 4];
    code[3] = list[data & 0x0f];
    return code;
}

int readtemp(int fd, unsigned char *buf, int len)
{
    int i, j, n;
    int cnt = 0;
    buf[0] = 0;
    for (i = 1; cnt < len; i++)
    {
        n = read(fd, buf + cnt, len - cnt);
        if (n == 0)
            break;
        printf("第%d次读取的数据为: ", i);
        for (j = 0; j < n; j++)
        {
            printf("%s", getcode(buf[cnt + j]));
            if (j + 1 < n)
                putchar(' ');
            else
                putchar('\n');
        }
        cnt += n;
    }
    return cnt;
}

void decode(unsigned char *buf)
{
    double temp;
    if (buf[1] & DSERR)
    {
        perror("但温度数据有误!\n");
        return;
    }
    temp = buf[2] * 1.00 + buf[3] * 0.01;
    if (buf[1] & DSNEG)
        temp = -temp;
    printf("温度值为: %.2lf\n", temp);
}

int main(void)
{
    unsigned char buf[4] = {0x83};
    int fd, n;
    struct termios t;
    
    fd = open("/dev/ttyUSB0", O_RDWR);
    if (fd == -1)
    {
        perror("打开串口失败!\n");
        return 0;
    }
    
    if (tcgetattr(fd, &t) == 0)
    {
        write(fd, buf, 1);
        n = readtemp(fd, buf, sizeof(buf));
        
        if (n != sizeof(buf))
            printf("传回的数据不完整,只读取了%d字节!\n", n);
        else if (buf[0] == 0x83)
        {
            printf("读取温度值成功!\n");
            decode(buf);
        }
        else
            printf("读取温度值失败, 错误码: %s\n", getcode(buf[0]));
    }
    else
        perror("获取串口默认配置失败!\n");
    
    close(fd);
    return 0;
}
一派護法 十九級
2樓 發表于:2017-2-6 16:34
$ ./debug
第1次读取的数据为: 0x83
第2次读取的数据为: 0xaf
第3次读取的数据为: 0x0e
第4次读取的数据为: 0x51
读取温度值成功!
温度值为: 14.81

一派護法 十九級
3樓 發表于:2017-2-6 16:36
今天才发现温度数据采集程序突然不工作了。硬件和串口线没有任何问题,是上位机程序的问题。因为现在(可能是某次系统更新后)用read函数不能保证一次性能读完所有数据,因此必须要采取多次读取的方法消除故障。

回復帖子

內容:
用戶名: 您目前是匿名發表
驗證碼:
(快捷鍵:Ctrl+Enter)
 

本帖信息

點擊數:348 回複數:2
評論數: ?
作者:巨大八爪鱼
最後回復:巨大八爪鱼
最後回復時間:2017-2-6 16:36
 
©2010-2024 Arslanbar Ver2.0
除非另有聲明,本站採用共享創意姓名標示-相同方式分享 3.0 Unported許可協議進行許可。