#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; }
|